前端框架的組件式開發永遠有一道鴻溝——跨組件通訊。我在 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
即可以顯示。