突然来了个项目要用redux,打的措手不及。。之前没用redux写过项目,现在要学一下。
整个应用只能有一个Store,包含项目中所有数据 生成Store createStore(fn) 想获得某个时点的数据State,就要对Store生成快照。可以通过store.getState()。一个State对应一个View。
View变化—>生成通知Action—>通过dispatch发出Action—>State变化 动作生成action,store发出dispatch将action传入,通知可以触发reducer action描述当前发生了什么事情,使用action会运送数据到Store const action={ type:’add’,//必须的,表示名称 pay:’learn’ } View要发什么消息,就有多少View。比如我input改变,触发的是同一个action,要改变的是store里面的同一个值。可以用action函数 function inputChange(value){ return { type:”input_change”, value } }
const action=inputChange(‘aaa’);
store.dispatch() View发出Action store.dispatch({ type:’input_change’, value:’aaa’ }) 这时候接受action为参数,发送出去。
然后store通过dispatch收到了action。需要给出新的state,即新的实时快照。 拿到数据要计算,所以计算的过程叫Reducer Reducer接受传过来的action和目前的state为参数,然后返回新的state
const reducer=function(state,action){ return new_state }
store.dispatch会触发Reducer的自动执行。因此,Store需要知道Reducer,这样在dispatch接受到action后能触发, 做法就是在生成Store时就将reducer传入 createStore(reducer)
store可以设置监听函数,state发生变化,则自动执行这个函数 store.subscribe()
mapStateToProps 把store里面的数据映射到connect当中关联的组件中去。 比如:
//store的数据: { text: '你好,访问者', name: '访问者', updateTime: 0 } //mapStateToProps函数 const mapStateToProps = (status)=>{ return { text: status.text, name: status.name, updateTime: status.updateTime } } //组件的使用 <div className="index"> <h3>{this.props.updateTime}</h3> <p>{this.props.text}</p> <input defaultValue={this.props.name} onChange={this.props.onChange} /> </div>mapDispatchToProps 接受方法触发dispatch,比如接受组件中的一个change方法触发dispatch改变store数据。
const mapDispatchToProps = (dispatch)=>{ return { onChange : (e)=>dispatch({ type:'change', payload:{ value: e.target.value, updateTime: new Date() }, }) } }connect 使用connect创建这个组件,并传入这两个函数。
export default connect(mapStateToProps,mapDispatchToProps)(MyComponent);