gpt4 book ai didi

javascript - 使用组合 reducer 时无法将状态映射到 Prop

转载 作者:行者123 更新时间:2023-12-03 01:16:07 27 4
gpt4 key购买 nike

我正在尝试使用 redux 将我的状态映射到给定组件。我有两个 reducer ,因此在将我的 rootReducer 传递到我的商店之前使用 mergeReducers。

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();

但是当我尝试将状态映射到给定组件的 props 时,状态未定义

const mapStateToProps = state => {
return {
ctr: state.ctr.counter,
storedResults: state.res.results //storedResults is undefined when I try to access it.
}
};

我的两个 reducer 如下所示:

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;

结果.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;

知道问题出在哪里吗?

最佳答案

结果缩减器中的初始状态是结果。只需将其更正为结果即可。

关于javascript - 使用组合 reducer 时无法将状态映射到 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006930/

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