前端框架的组件式开发永远有一道鸿沟——跨组件通讯。我在 Vue 教程中有提到过,若是对跨组件通讯不明白的可先跳过去看看。javascript
React 不一样与双向数据绑定框架,它是单向数据流,因此每次更新都得调用setState
,因此在跨组件通讯中会比较迂回。还有就是 React 没有逻辑分层,在开发过程当中,逻辑分层是很重要的。前端
Redux 实现了跨组件通讯和逻辑分层的好处,因此在 React 中使用 Redux 更配。java
为了说明问题,先来一个公共对象实现跨组件通讯。固然这个也是 flux 的实现原理。react
export default { increment(){ return { type: "+" } }, decrement(){ return { type: '-' } } }
export default (state = 0, action) => { switch(action.type){ case '+': return state + 1; case '-': return state - 1; default: return state; } }
import React, {Component} from 'react' import {createStore} from 'redux' import Actions from './actions' import Reducer from './reducer' const store = createStore(Reducer); export default class Component1 extends Component{ constructor(props){ super(props); this.state = {count: 0} } increment = () => { store.dispatch(Actions.increment()); this.setState({ count: store.getState() }) } render(){ return ( <div> <h3>component-cp1-{this.state.count}</h3> <input type="button" value="increment" onClick={this.increment}/> </div> ) } }
Actions 层redux
store.dispatch(Actions.increment());
function
且必须返回有type
属性的对象store
进行派发。Reducer 层segmentfault
state
,另外一个为action
return
的结果能够用store.getState()
来接收Store 层前端框架
redux
的一个方法,接受reducer
,返回一个对象store
store
的方法dispath
用于派发action
dispath
派发的action
会触发reducer
View 层框架
getState()
获取的值而后再setState
即可以显示。