實(shí)例地址:https://github.com/ws199501/react-redux-demo
redux: action+reducer, 使用connect(mapStateToProps綁定state, mapDispatchToProps綁定action)
configureStore文件中結(jié)合寫好的reducer在中間件的幫助下生成store, 這里配置會(huì)用到一些api在https://redux.js.org/api-reference/combinereducers文檔中都有說(shuō)明。我理解起來(lái)就是更優(yōu)的create一個(gè)store梦重。
先貼我的項(xiàng)目運(yùn)行結(jié)果:
action.getUser
action.changeUser
配置內(nèi)容:
configureStore
App 頁(yè)面:<Provider store={configureStore()}>
Provider 說(shuō)明:https://github.com/reactjs/react-redux/blob/HEAD/docs/api.md#provider-store
簡(jiǎn)單來(lái)說(shuō)就是配合connect的好選擇傀履。
Normally, you can’t use connect() without wrapping a parent or ancestor component in <Provider>
我英語(yǔ)其實(shí)比較差村刨,所以閱讀英文文檔還是很吃力的糯耍,我理解的是這個(gè)是在頁(yè)面之間傳遞,綁定store而使用,所以這個(gè)就必須穿在兩個(gè)及以上的頁(yè)面中使用栗柒。只有父級(jí)擁有Provider 傳入 store 子頁(yè)面才能使用connect陵像。
main 頁(yè)面:
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 接受傳來(lái)的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 一些需要的東西。
項(xiàng)目里寫了兩個(gè)action刁赖,通過(guò)reducer改變同一個(gè)state搁痛。
componentDidMount() {
//發(fā)送action,經(jīng)過(guò)reducers派發(fā),改變state
this.props.actions.getUser()
}
componentDidMount() {
//發(fā)送action,經(jīng)過(guò)reducers派發(fā),改變state
this.props.actions.getUser()
}
handleChange() {
this.props.actions.changeUser(this.message)
}
可以拷下項(xiàng)目運(yùn)行一下,流程輸出應(yīng)該就比較明顯了宇弛。