gpt4 book ai didi

javascript - 避免重复州名

转载 作者:行者123 更新时间:2023-11-30 11:46:29 26 4
gpt4 key购买 nike

假设我有一个如下所示的 rootreducer

const rootR = combineReducers({
topics,
...
});

主题 reducer

function topics(state = { topics=[], error: null}, action){
switch (action.type){
case types.FETCH_TOPICS_SUCCESSFULLY:
const { topics } = action;
return {
...state,
topics,
};
default:
return state;
}
};

当我触发相关操作时,我得到具有可重复属性的状态 state.topics.topics 而不是 state.topics

有什么办法可以避免这种重复(topics.topics)?

提前致谢

最佳答案

查看 topics reducer 的 initialState,topics reducer 可访问的状态对象具有以下结构:

{
topics: [],
error: null
}

所以当您像这样组合Reducers时:

const rootR = combineReducers({
topics,
anotherReducer,
someOtherReducer.
// ...
});

生成的全局应用状态将如下所示:

{
topics: {
topics: [],
error: null
},
anotherReducer: {
// ...
},
someOtherReducer: {
// ...
},

// ...
}

所以如果你想从全局状态访问topics数组,你需要做state.topics.topics

state.topics 下有两个东西,topics 数组和error。因此,让我们将第二个 topics 键重命名为 items 以避免混淆。(难免要有第二个key来存放数组,因为你也想要error)

因此我们有:

state.topics = {
items: [],
error: null,
}

现在我们访问 state.topics.items 而不是 state.topics.topics

为实现这一点,传递给 topics reducer 的 initialstate 必须是:

function topics(state = { items = [], error: null }, action){
//...
}

现在在 reducer FETCH_TOPICS_SUCCESSFULLY 中,我们想要将数组 action.topics 附加到 items,就像这样(不改变我们的当前状态):

case types.FETCH_TOPICS_SUCCESSFULLY:
const { topics } = action;
return {
...state,
items: [
...state.items,
...topics
],
};

关于javascript - 避免重复州名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40851685/

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