项目目录整个项目目录分为三部分如图:Redux分为{Action,Reducer,Store}入口文件为App.jsx项目效果可见从图中可以看出整个组件可以分为3个组件,内部的Counter组件、Count-calculatingSummary组件和整个容器组件ControlPanelContentReactRedux其实是两个独立的产品。应用程序可以在没有Redux的情况下使用React,或者在没有React的情况下使用Redux。但是,如果两者结合,没有理由不使用一个叫做react-redux的库,它可以大大简化代码的编写;react-redux的两个主要功能:connect:连接数据处理组件和内部UI组件;Provider:提供包含store的上下文;通过Content传递Store的目的是先定义Action/index.jsxexportconstIncrement='increment'exportconstDecrement='decrement'exportconstincrement=(counterCaption)=>({type:Increment,counterCaption})exportconstdecrement=(counterCaption)=>({type:Decrement,counterCaption})Reducer/index.jsximport{Increment,Decrement}from'../Action'exportdefault(state,action)=>{const{counterCaption}=actionswitch(action.type){case增量:return{...state,[counterCaption]:state[counterCaption]+1}case减量:return{...state,[counterCaption]:state[counterCaption]-1}默认:返回状态}}Store/store.jsximport{createStore}from'redux'importreducerfrom'../Reducer'constinitValue={'First':0,'Second':10,'Third':20}conststore=createStore(reducer,initValue)exportdefaultstore在action中,我们会发现定义了两个常量,一个控制增加,另一个控制减少,然后暴露出增加和减少的函数这两个函数可以在Couter组件中调用constbuttonStyle={margin:"20px"}functionCounter({caption,Increment,Decrement,value}){return(
+<按钮样式={buttonStyle}onClick={Decrement}>-{caption}计数:{value}
)}functionmapState(state,ownProps){return{value:state[自己的道具。caption]}}functionmapDispatch(dispatch,ownProps){return{Increment:()=>{dispatch(increment(ownProps.caption))},Decrement:()=>{dispatch(decrement(ownProps.caption))}}}exportdefaultconnect(mapState,mapDispatch)(Counter)1.在counter组件中,我们会发现引入了increase和decrease两个函数,然后在mapDispatch函数中调用,暴露出一个与increase合并的对象并递减,然后在Counter函数组件中通过解构得到通过mapDispath包传递的增减组件的mapDispatch函数的作用是将内层功能组件的增减动作调度到Store。然后我们转过来看到Reducer/index.jsx这个reducer是专门处理数据逻辑的。通过传入(state,action),针对不同的action返回不同的store对象。Store/store.js是商店的特殊包。通过传入reducer并通过createStore方法初始化状态(initValue)来暴露存储对象。该对象不是原始存储对象。该对象注册了原始商店并添加了几个方法。要了解更多关于这个方法,请**点击这里**[https://github.com/reactjs/redux/blob/master/src/createStore.js][1]最后,将store对象暴露给App.jsx在主入口进行调用importReact,{Component,PropTypes}from'react';从'react-dom'导入ReactDOM,{render};importstorefrom'./Redux/Store/Store.jsx'import{Provider}from'react-redux';importControlPanelfrom'./Component/ControlPanel.jsx'import'./style/common.less'render(
,document.body.appendChild(document.createElement('div')));我们将react-redux提供的顶层组件Provider传入store,然后将要显示的ControlPanel写入顶层组件。Provider为所有子组件提供了整个全局的store,调用具体代码实现请gitclonehttps://github.com/jeromehan/...