Redux - 在哪里准备数据 [英] Redux - where to prepare data

查看:33
本文介绍了Redux - 在哪里准备数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Redux 的新手,但遇到了问题.我有一个对象数组,在该数组中添加一个新对象后,我想更改所有其他对象.例如,像这样:

I am new in Redux and I have a problem. I have array of objects in state, after adding a new object in that array I want to change all other objects. For example, something like this:

[{id : 0, visible: false}, {id : 1, visible: true}] - old array
[{id : 0, visible: false}, {id : 1, visible : false}, {id : 2, visible : true}] - that I want

我应该在哪里准备旧状态?正如 redux 文档所说,在减速器中,我不应该用状态做任何事情,我只需要返回新状态.我可以在 reducer 中编写函数,准备先前状态的副本并作为新状态返回吗?类似的东西:

Where I should prepare old state? As redux documentaion said, in reducers I shouldn't make anything with state, I just need to return new state. Can I write functions in reducers, which will prepare copy of previous state and return as new state? Something like:

export function ui(state = initialState, action){
switch (action.type){
  case "SOME_ACTION" :
    var newState = someFunction(state.items, action)
    return Object.assign({}, state, {
      items : newState
    });
  default:
     return state;
  }}

function someFunction(array, action){
    .... some code
    return newArray
}

或者我应该把这个功能放在另一个地方?编辑状态数据的最佳做法是什么?

Or I should keep this function in another place? What are the best practices to edit data in state?

推荐答案

所有对 state 的修改都应该在你的 reducer 中完成.当您以不可变的方式进行操作时,返回新状态和修改旧状态是一回事.也就是说,新状态是来自旧状态的数据,可能是修改过的,并带有新数据.

All modifications to state should be done in your reducer. Returning a new state, and modifying the old state are the same thing when you're doing it in an immutable way. That is, the new state IS the data from the old state, perhaps modified, and with new data.

以您的示例为例,我可能会执行以下操作:

Given your example I might do something like:

function rootReducer(state = initialState, action) {
 switch(action.type) {
   case: "SOME_ACTION":
    var allStateVisibleFalse = state.map(x => Object.assign({}, x, { visible: false} ));
    return [...allStateVisibleFalse, { id: 2, visible: true}];
 }
 ...
}

这篇关于Redux - 在哪里准备数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆