Redux - where to prepare data

2019-07-07 18:54发布

问题:

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