我正在尝试通过redux将状态映射到给定的组件。我有两个reducer,因此在将rootReducer传递到商店之前正在使用CombineReducers。
const rootReducer = combineReducers({
ctr:counter,
res:result
});
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));
registerServiceWorker();
但是当我尝试将状态映射到给定组件的道具时,状态是不确定的
const mapStateToProps = state => {
return {
ctr: state.ctr.counter,
storedResults: state.res.results //storedResults is undefined when I try to access it.
}
};
我的两个减速器如下:
counter.js
import * as actionTypes from "../actions";
const initialState = {
counter:0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.INCREMENT:
return {
...state,
counter: state.counter + 1
};
case actionTypes.DECREMENT:
return {
...state,
counter: state.counter - 1
};
case actionTypes.ADD:
return {
...state,
counter: state.counter + action.val
};
case actionTypes.SUBTRACT5:
return {
...state,
counter: state.counter - 5
};
}
return state;
};
export default reducer;
result.js
import * as actionTypes from "../actions";
const initialState = {
result:[]
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.STORE_RESULT:
return {
...state,
results:state.results.concat({id: new Date(), value:state.counter})
};
case actionTypes.DELETE_RESULT:
// const id = 2;
// const newArray = [...state.results];
// newArray.splice(id,1);
const updatedArray = state.results.filter(result => result.id !== action.resultId);
return {
...state,
results:updatedArray
}
}
return state;
};
export default reducer;
知道可能是什么问题吗?
答案 0 :(得分:1)
您在结果约简器中的initialState为result
。只需将其更正为results
。