我仍然在思考函数式编程以及如何从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"
}我的减速机看起来像这样
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"
}发布于 2017-01-17 01:59:53
如果您的对象的所有值每次都在更改,您可以简单地将新的有效负载作为新状态返回。但是如果只有一些值发生了变化,那么您可以使用ES6、Object.assign或object-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;
}
}发布于 2017-01-17 01:44:29
只需使用非可变函数并返回新的数据结构即可。
如果你的状态是简单的{a: 1,b: 2,c: 3},你想让它变成{a: 4,b: 5,c: 6},只需返回{a: 4,b: 5,c: 6}。
function reducer(state = {a: 1, b: 2, c: 3}, action){
switch(action.type) {
case 'GET_MOVIE':
return action.payload // assuming action.payload = {a: 4, b: 5, c: 6}
default:
return state;
}
}当您想要新状态= {a:1,b:2,c:3},{a:4,b:5,c: 6}时,它会变得更有趣。
对于可变函数和非可变函数的良好列表,这是很有帮助的:https://jeff.is/blog/mutative-vs-non-mutative-array-methods-in-js.html
我还发现React的不变性帮助器非常适合深度嵌套的结构。它们使用Mongo风格的语法。
发布于 2017-01-17 02:11:28
我有点困惑,为什么在处理对象时需要数组运算符。在这种当前状态下,您可以通过以下两种方式之一完成此操作,具体取决于您的构建工具、polyfills和/或目标浏览器。
使用Object.assign()
function reducer(state = {}, action){
switch(action.type) {
case 'GET_MOVIE':
return Object.assign({}, state, {
Actors: action.Actors,
Awards: action.Awards,
Country: action.Country,
Director: action.Director
});
default:
return state;
}
}或者使用扩展运算符...
function reducer(state = {}, action){
switch(action.type) {
case 'GET_MOVIE':
return {
...state,
Actors: action.Actors,
Awards: action.Awards,
Country: action.Country,
Director: action.Director
}
default:
return state;
}
}https://stackoverflow.com/questions/41682046
复制相似问题