react redux 配置

實(shí)例地址:https://github.com/ws199501/react-redux-demo
redux: action+reducer, 使用connect(mapStateToProps綁定state, mapDispatchToProps綁定action)
configureStore文件中結(jié)合寫(xiě)好的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)目里寫(xiě)了兩個(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)該就比較明顯了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容