我在单独的文件夹中有两个化简器,用于类似于此结构的单独组件:
index.js
/componentOne
|_ componentOne.js
|_ componentOneActionCreator.js
|_ componentOneReducer.js
/componentTwo
|_ componentTwo.js
|_ componentTwoActionCreator.js
|_ componentTwoReducer.js
当我在
createStore
中输入index.js
(它们在import
中)时,这些Reducer均在应用程序中单独工作-但是,如果我尝试使用combineReducers()
组合它们,则它们的功能都不起作用(不会但不能破坏用户界面)。我认为这与状态有关-下面提供了更多代码供参考: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}
}
当将状态映射到道具时,您应该使用例如
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;
}
}