Redux - where to prepare data

本小妞迷上赌 提交于 2019-12-24 02:45:23

问题


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

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?


回答1:


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}];
 }
 ...
}


来源:https://stackoverflow.com/questions/35430389/redux-where-to-prepare-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!