整個項目目錄分爲圖中所示: Redux分爲{Action,Reducer,Store} 入口文件爲App.jsx
從圖中能夠看出整個組件能夠分爲3個組件,內部Counter組件,計算Count的Summary的組件,以及整個容器組件ControlPanel
React Redux 事實上是兩個獨立的產品, 應用可使用 React 而不使用 Redux ,也可使用 Redux 而不使用 React ,可是,若是二者結合使用,沒有理由不使用 一個名叫 react-redux 的庫這個庫可以大大簡化代碼的書寫; react-redux 的兩個最主要功能: connect :鏈接數據處理組件和內部UI組件; Provider :提供包含 store的context; 經過Content實現傳遞Store的目的 首先定義好
Action/index.jsxreact
export const Increment='increment' export const Decrement='decrement' export const increment=(counterCaption)=>({ type:Increment, counterCaption } ) export const decrement=(counterCaption)=>({ type:Decrement, counterCaption })
Reducer/index.jsxgit
import {Increment,Decrement} from '../Action' export default(state,action)=>{ const {counterCaption}=action switch (action.type){ case Increment: return {...state,[counterCaption]:state[counterCaption]+1} case Decrement: return {...state,[counterCaption]:state[counterCaption]-1} default: return state } }
Store/store.jsxgithub
import {createStore} from 'redux' import reducer from '../Reducer' const initValue={ 'First':0, 'Second':10, 'Third':20 } const store=createStore(reducer,initValue) export default store
在action中咱們會發現定義了兩個常量,一個控制增長,一個控制減小,而後暴露出增長減小的函數。這兩個函 數能夠在Couter組件中調用
Counter.jsxredux
import React, { Component } from 'react' import {increment,decrement} from '../Redux/Action' import {connect} from 'react-redux'; const buttonStyle = { margin: "20px" } function Counter({caption, Increment, Decrement, value}){ return ( <div> <button style={buttonStyle} onClick={Increment}>+</button> <button style={buttonStyle} onClick={Decrement}>-</button> <span>{caption} count :{value}</span> </div> ) } function mapState(state,ownProps){ return{ value:state[ownProps.caption] } } function mapDispatch(dispatch,ownProps){ return { Increment:()=>{ dispatch(increment(ownProps.caption)) }, Decrement:()=>{ dispatch(decrement(ownProps.caption)) } } } export default connect(mapState,mapDispatch)(Counter)
1.在counter組件中咱們會發現引入了增長和減小這兩個函數,而後在mapDispatch函數中進行調用,暴露出增 加和減小合併的一個對象,而後經過解構在Counter函數組件中得到傳遞過來的通過mapDispath包裝事後的增 加和減小組件。mapDispatch函數的做用就是把內層函數組件的增長和減小的動做派發給Store 而後咱們轉過來看Reducer/index.jsx reducer是專門處理數據邏輯的,經過傳入(state,action),針對不一樣的action返回一個不一樣的store對象
Store/store.js數組
是專門對store進行的一個封裝,經過createStore方法傳入reducer和初始化state(initValue)來暴露 store對象,此對象非原始的store對象,該對象是對原始store進行註冊,增長了若干方法。具體瞭解此方法能夠**請戳這裏**
[https://github.com/reactjs/redux/blob/master/src/createStore.js][1]
最後把store對象暴露給App.jsx在主入口進行調用
import React, {Component, PropTypes} from 'react'; import ReactDOM, {render} from 'react-dom'; import store from './Redux/Store/Store.jsx' import {Provider} from 'react-redux'; import ControlPanel from './Component/ControlPanel.jsx' import './style/common.less' render( <Provider store={store}> <ControlPanel /> </Provider>, document.body.appendChild(document.createElement('div')) );
咱們經過react-redux提供的頂層組件Provider傳入store而後把要展現的ControlPanel寫入頂層組件就好了, Provider提供了整個全局的store供全部的子組件進行調用
具體代碼實現請git clone
https://github.com/jeromehan/...app