安装

npm i -S redux react-redux redux-devtools

概念

在redux中分为3个对象:Action、Reducer、Store

Action

  1. 对行为(如用户行为)的抽象
  2. Action 就是一个普通 JavaScript 对象。如:{ type: 'ADD_TODO', text: 'Go to swimming pool' }(其中type字段是约定也是必须的)
  3. 作为Reducer的参数

Reducer

  1. 一个普通的函数,用来修改store的状态。
  2. 函数签名:(currentState,action)=>newState
    1. 在 default 情况下返回currentState
    2. Object.assign({},state, { visibilityFilter: action.filter })(第一个参数不能为state) 等价于ES7的 { ...state, ...newState }
  3. redux 的 combineReducers 方法可合并reducer

Store

  1. 代表数据模型,内部维护了一个state变量
  2. 两个核心方法,分别是getState、dispatch。前者用来获取store的状态(state),后者用来修改store的状态
  3. createStore(reducer) 可创建Store

redux示例:

import { createStore } from 'redux'

// reducer
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
default:
return state
}
} // state
let store = createStore(counter); // 会调用 // 监听
store.subscribe(() =>
console.log(store.getState())
); // 调用reducer
store.dispatch({ type: 'INCREMENT' });

react-redux

react的需求:

  1. 数据总是单向从顶层向下分发的
  2. 组件之间的沟通通过提升state:子组件改变父组件state的办法只能是通过onClick触发父组件声明好的回调
  3. state越来越复杂:单页应用的发展导致。包括服务器响应、缓存数据、本地生成尚未持久化到服务器的数据,也包括 UI 状态,如激活的路由,被选中的标签,是否显示加载动效或者分页器等等。

react-redux 将react组件分为2种:展示组件 和 容器组件

展示组件

描述如何展示:负责UI样式的展示

  1. 数据来源:props
  2. 数据修改:通过props的回调函数
  3. 不直接使用redux

容器组件

描述如何运行:负责数据获取 和 状态更新

  1. 数据来源:redux state
  2. 数据修改:redux 派发action
  3. 直接使用redux

react-redux 只有2个API:Provider 和 connect

Provider

<Provider store>

  1. 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
  2. 接收Redux的store作为props,内部通过context对象传递给子孙组件上的connect

connect

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])(Component)

作用:连接React组件与 Redux store

mapStateToProps(state, ownProps) : stateProps

  1. 将 store 中的数据作为 props 绑定到组件上。
  2. 当 state 变化,或者 ownProps 变化的时候,mapStateToProps 都会被调用,计算出一个新的 stateProps

mapDispatchToProps(dispatch, ownProps): dispatchProps:将 dispatch(action) 作为 props 绑定到组件上

mergeProps:指定 stateProps 以及 dispatchProps 合并到 ownProps 的方式。(默认使用Object.assign)

connect是个高阶组件(HOC)大致源码:

export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
return function wrapWithConnect(WrappedComponent) {
class Connect extends Component {
constructor(props, context) {
this.store = props.store || context.store
this.stateProps = computeStateProps(this.store, props)
this.dispatchProps = computeDispatchProps(this.store, props)
this.state = { storeState: null }
// 合并stateProps、dispatchProps、parentProps
this.updateState()
}
shouldComponentUpdate(nextProps, nextState) {
// 进行判断,当数据发生改变时,Component重新渲染
if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
this.updateState(nextProps)
return true
}
}
componentDidMount() {
this.store.subscribe( () => this.setState({ storeState: this.store.getState() }) )
}
render() {
return (
<WrappedComponent {...this.nextState} />
)
}
}
return Connect;
}
}

react-redux示例:

Counter.js

import React, { Component } from 'react';
import { createStore, bindActionCreators } from 'redux';
import { Provider, connect } from 'react-redux'; function clickReduce(state = { todo: 1 }, action) {
switch (action.type) {
case 'click':
return Object.assign({}, state, { todo: state.todo + 1 });
default:
return state;
}
} let store = createStore(clickReduce); class Counter extends Component {
render() {
return (
<div>
<div>{this.props.todo}</div>
<button onClick={this.props.clickTodo}>Click</button>
</div>
)
}
} // 方式1:
export default connect(state => ({ todo: state.todo }),
dispatch => ({ clickTodo: () => dispatch({ type: 'click' }) }))(Counter) // 方式2:
export default connect(state => ({ todo: state.todo }),
dispatch => bindActionCreators({ clickTodo: () => ({ type: 'click' }) }, dispatch))(Counter);

index.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import Clock from './Clock' render((
<Provider store={store}>
<Counter />
</Provider>), root);

在redux中,我们只能dispatch简单的action对象。

对应的在react-redux中,我们只能定义同步的reducer方法。

下节将介绍在react-redux如何定义异步方法。让其更加适用于生产环境。

React从入门到放弃之前奏(3):Redux简介的更多相关文章

  1. React从入门到放弃之前奏(5):ReactRouter4

    概念 安装:npm i -S react-router react-router-dom GitHub:ReactTraining/react-router React Router中有三种类型的组件 ...

  2. React从入门到放弃之前奏(1):webpack4简介

    接触webpack是好久之前的事情了,最近看了下webpack没想到都到4了. webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler). 会创建1个 ...

  3. React从入门到放弃之前奏(2):React简介

    本系列将尽可能使用ES6(ES2015)语法.所以均在上节webpack的基础上做开发. React是Facebook开发的一款JS库,因为基于Virtual DOM,所以响应速度快,以及支持跨平台. ...

  4. React从入门到放弃之前奏(4):Redux中间件

    redux 提供了类似后端 Express 的中间件概念. 最适合扩展的是redux中的 store.dispatch 方法,中间件实际就是通过 override redux的store.dispat ...

  5. 在 2016 年学 JavaScript 是一种什么样的体验?(React从入门到放弃)

    jquery 年代 vs 前端模块化 http://blog.csdn.net/offbye/article/details/52793921 ++ 嘿,我最近接到一个 Web 项目,不过老实说,我这 ...

  6. ubuntu-docker入门到放弃(七)Dockerfile简介

    一.dockerfile基本结构 最简单的理解就是dockerfile实际上是一些命令的堆叠,有点像最基础的shell脚本,没有if 没有for,就是串行的一堆命令. 一般而言,dockerfile分 ...

  7. D3.js从入门到“放弃”指南

    前言 近期略有点诸事不顺,趁略有闲余之时,玩起D3.js.之前实际项目中主要是用各种chart如hightchart.echarts等,这些图形库玩起来貌都是完美的,一切皆可配置,但几年前接触了D3之 ...

  8. 一天带你入门到放弃vue.js(一)

    写在前面的话! 每个新的框架入手都会进行一些列的扯犊子!这里不多说那么多!简简单单说一下vue吧! Vue.js是目前三大框架(angular,vue,react)之一,是渐进式js框架,据说是摒弃了 ...

  9. 小白学 Python 爬虫(28):自动化测试框架 Selenium 从入门到放弃(下)

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

随机推荐

  1. rails中select不能响应多选的解决办法

    在rails4.2中如果你写如下代码,post的select无法传回多选内容,即使你select设置为多选: <select id='id_size' name='name_size' mult ...

  2. Configure the MySQL account associate to the domain user via MySQL Windows Authentication Plugin

    在此记录如何将之前一次做第三发软件在配置的过程. 将AD user通过代理映射到mysql 用户. 在Mysql官网有这样一段话: The server-side Windows authentica ...

  3. Tihinkphp3.2整合最新版阿里大鱼进行短信验证码发送

    阿里大鱼最新下载地址:阿里大鱼SDK下载 或者从官网进行下载:阿里大鱼SDK官网下载 下载完成后,将压缩包内的api_sdk文件夹放到ThinkPHP\Library\Vendor目录下,修改文件名为 ...

  4. innobackupex 简单使用笔记

    innobackupex 选项介绍 --backup 备份 --apply-log   应用日志 --move-back  --copy-back 恢复 --export 只导出单个表.前提是使用in ...

  5. Google揭开Mesa的神秘面纱——一个具备跨地域复制和近实时特性的可伸缩数据仓库

    http://www.infoq.com/cn/news/2014/08/google-data-warehouse-mesa Google发表了一篇新的论文,该论文描述了他们内部所使用的一个被称为M ...

  6. (译)WebRTC实战: STUN, TURN, Signaling

    http://xiaol.me/2014/08/24/webrtc-stun-turn-signaling/ 原文:WebRTC in the real world: STUN, TURN and s ...

  7. postgresql 异步流复制hot standby搭建

    先说说环境,主从库版本都是9.5,主库在CentOS物理机上,从库在Ubuntu虚拟机上 一.主库上的操作: 1.添加同步访问规则: host   replication     dbuser     ...

  8. 遍历php数组的几种方法

    第一.foreach() foreach()是一个用来遍历数组中数据的最简单有效的方法. <?php $urls= array('aaa','bbb','ccc','ddd'); foreach ...

  9. js对象属性值为对象形式取值方式

    console.log(rowData);//取带点的属性值 console.log(rowData['layoutPipegallery.pipegallerycode']);//取带点的属性值

  10. 架构之微服务(zookeeper)

    ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,它包含一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命名服务等.Zookeeper是hadoop的一个子项目,其 ...