我在单独的文件夹中有两个reducer用于与此类似的结构中的单独组件:
index.js
/componentOne
|_ componentOne.js
|_ componentOneActionCreator.js
|_ componentOneReducer.js
/componentTwo
|_ componentTwo.js
|_ componentTwoActionCreator.js
|_ componentTwoReducer.js
这些Reducers中的每一个都在应用内单独工作 - 当我createStore
index.js
时(import
进入combineReducers()
) - 但如果我尝试使用{组合它们{1}},它们的功能都不起作用(但不会破坏用户界面)。我认为这与州有关 - 下面有一些代码供参考:
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);
我在这里缺少什么想法?
答案 0 :(得分:5)
我怀疑你的问题是没有使用状态树键。通过在示例中使用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;
}
}
并直接做一些不可变的事情。
{{1}}