gpt4 book ai didi

javascript - 使用Reducer Redux中的新内容更新数组

转载 作者:行者123 更新时间:2023-12-03 05:14:02 28 4
gpt4 key购买 nike

我仍在研究函数式编程以及如何从 reducer 返回非变异对象。

我正在尝试替换 reducer 中旧对象的内容,而不改变旧状态。

所以如果旧状态是

 {
Actors:"Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl"
Awards:"Won 1 Oscar. Another 9 wins & 22 nominations."
Country:"USA, UK"
Director:"Tim Burton"
}

新状态是

{
Actors:"George Clooney"
Awards:"Won 9 Oscars."
Country:"USA"
Director:"Quentin Tarantino"
}

我的 reducer 看起来像这样

function reducer(state = {}, action){
switch(action.type) {
case 'GET_MOVIE':
return //new Array here that has not been mutatated
default:
return state;
}
}

我的有效负载如下所示

{
Actors:"Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl"
Awards:"Won 1 Oscar. Another 9 wins & 22 nominations."
Country:"USA, UK"
Director:"Tim Burton"
}

最佳答案

如果对象的所有值每次都在变化,您可以简单地将新的有效负载作为新状态返回。但如果只有部分值发生变化,那么您可以使用 ES6 Object.assignobject-assign作为 npm 模块。

如果所有值每次都在变化,

function reducer(state = {}, action){
switch(action.type) {
case 'GET_MOVIE':
return action.payload;
default:
return state;
}
}

如果某些值发生变化,

function reducer(state = {}, action){
switch(action.type) {
case 'GET_MOVIE':
// let say Actors field changed, then
return Object.assign({}, state, {Actors: "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl" });
default:
return state;
}
}

关于javascript - 使用Reducer Redux中的新内容更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682046/

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