实例地址:https://github.com/ws199501/react-redux-demo
redux: action+reducer, 使用connect(mapStateToProps绑定state, mapDispatchToProps绑定action)
configureStore文件中结合写好的reducer在中间件的帮助下生成store, 这里配置会用到一些api在https://redux.js.org/api-reference/combinereducers文档中都有说明。我理解起来就是更优的create一个store。
先贴我的项目运行结果:
action.changeUser
配置内容:
configureStore
App 页面:<Provider store={configureStore()}>
Provider 说明:https://github.com/reactjs/react-redux/blob/HEAD/docs/api.md#provider-store
简单来说就是配合connect的好选择。
Normally, you can’t use connect() without wrapping a parent or ancestor component in <Provider>
我英语其实比较差,所以阅读英文文档还是很吃力的,我理解的是这个是在页面之间传递,绑定store而使用,所以这个就必须穿在两个及以上的页面中使用。只有父级拥有Provider 传入 store 子页面才能使用connect。
main 页面:
export default connect(mapStateToProps, mapDispatchToProps)(Home)
Actions are plain JavaScript objects
export function getUser(opt = {}) {
return (dispatch) => {
console.log('action -->',dispatch)
dispatch({ type: "TEST", result: "我是得到原始的user信息,啦啦啦~" })
}
}
reducer 接受传来的state和action,返回改变后的state
export function user(state = {payload: false}, action) {
console.log('reducer -->', state, action)
switch (action.type) {
case "TEST":
return {
payload: true,
message: action.result
}
default:
return state
}
}
到这里就配置完毕了,别忘了npm install 一些需要的东西。
项目里写了两个action,通过reducer改变同一个state。
componentDidMount() {
//发送action,经过reducers派发,改变state
this.props.actions.getUser()
}
componentDidMount() {
//发送action,经过reducers派发,改变state
this.props.actions.getUser()
}
handleChange() {
this.props.actions.changeUser(this.message)
}
可以拷下项目运行一下,流程输出应该就比较明显了。
网友评论