回忆原本redux的写法
1.创建store
let store = createStore(reducer)
3、编写action来触发对应的reducer
let action= {
type:'aAction'
}
2、编写reducer 执行action对应的行为,返回一个新的state给store
let reducer= (state,action)=>{
switch(action){
case 'aAction':
return newState
}
}
3、在页面中触发事件来发起一个action
onClick(){
store.dispatch(action)
}
以上是redux管理状态的方式。
要在组件中获取状态:
this.state={...store.getState()}
要在更新状态的同时更新试图:
store.subscribe(() =>{
console.log(this)
this.setState({...store.getState()})
});
组件一多,你就会发现重复代码越来越多,为了避免这种情况的发送,redux提供了react-redux。
react-redux
react-redux的出现是为了react更方便的使用redux。
首先它提供了Provider组件
<Provider store={store}>
<compenentA />
<compenentB />
.
.
.
.
</Provider>
这样该组件下的所有子组件都有能力通过connect方法获取store中的状态了。(原理是react的context特性)
connect
connect方法接受两个函数作为实参内部调用,返回一个新的函数
1、mapStateToProps函数
mapStateToProps函数接受store中的状态作为参数.
const mapStateToProps = (state) => {
return {
...state
}
}
2、mapDispatchToProps函数
mapDispatchToProps函数接受dispatch方法作为参数.
const mapDispatchToProps = (dispatch) => {
return {
func1(e) {
let action = {
type: 'action1'
}
dispatch(action)
},
func2(e) {
let action = {
type: 'action2'
}
dispatch(action)
}
}
}
connect执行后会返回一个函数,该函数把组件作为实参,把mapStateToProps,mapDispatchToProps两个函数返回值作为props重新包装,改装组件(其实就是高阶组件把)返回一个新的组件.
这就是react-redux的使用方法。