gpt4 book ai didi

javascript - 无法组合Reducers()

转载 作者:行者123 更新时间:2023-11-28 12:17:30 25 4
gpt4 key购买 nike

我在单独的文件夹中有两个 reducer ,用于结构类似的单独组件:

index.js
/componentOne
|_ componentOne.js
|_ componentOneActionCreator.js
|_ componentOneReducer.js
/componentTwo
|_ componentTwo.js
|_ componentTwoActionCreator.js
|_ componentTwoReducer.js

这些Reducers中的每一个都在应用程序中单独工作 - 当我在index.jscreateStore时(它们被导入) -但如果我尝试使用 combineReducers() 组合它们,它们的函数都不起作用(但是不会破坏 UI)。我认为这与状态有关 - 下面还有一些代码可供引用:

index.js

const rootReducer = combineReducers({
componentOneReducer,
componentTwoReducer
});

let store = createStore(rootReducer, applyMiddleware(thunk))

componentOneReducer

export default(state = {}, payload) => {

let newState = JSON.parse(JSON.stringify(state));

switch (payload.type) {
case 'REQUEST_DATA':
newState.isLoading = true;
return newState;
case 'RECEIVE_DATA':
newState.isLoading = false;
newState.pageData = payload.payload;
newState.pageName = payload.payload.pageName;

return newState
default:
return state;
}
}

componentTwoReducer.js 与 componentOneReducer.js 非常相似,但不完全相同。

componentOne.js

    return (
<Layout>
<section>
<SectionHeader headerText={this.props.pageName}></SectionHeader>

....

function mapStateToProps(state, props) {
return {
pageName: state.pageName
}
}

function mapDispatchToProps(dispatch) {
return {
actions: {
getData: function() {
dispatch(getData());
}
}
}
}

export default connect(mapStateToProps, mapDispatchToProps) (componentOne);

我在这里缺少什么想法吗?

最佳答案

我怀疑您的问题是不使用状态树键。通过使用您的示例中的combineReducers,生成的状态树将由reducer命名。由于对象简写 { componentOneReducer } 变为 { componentOneReducer: componentOneReducer },而您可以显式地将其更改为例如{ reducerOne: componentOneReducer }

因此你的状态变成这样:

{
componentOneReducer: {loading: false, pageData: 123},
componentTwoReducer: {loading: true, pageData: null}
}

将状态映射到 Prop 时,您应该使用例如

const mapStateToProps = state => ({
loading: state.componentOneReducer.loading
pageData: state.componentOneReducer.pageData
})

并在组件中执行this.props.loading

我还建议您放弃使用 JSON.parse(JSON.stringify(state)) 并直接执行一些不可变的操作。

export default(state = {}, payload) => {
switch (payload.type) {
case 'REQUEST_DATA': {
return {
...state,
isLoading: true;
};
}
case 'RECEIVE_DATA': {
return {
...state,
isLoading: false,
pageData: payload.payload,
pageName: payload.payload.pageName
}
}
default:
return state;
}
}

关于javascript - 无法组合Reducers(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com