Change reduction state, but also preserve some old state values

In my React-Redux app, I change the reduction stateand looks something like this:

state {
    key1: oldVal1
    key2: oldArray1 //The value here is an array
    .
    .
    .
}

Now, when I update the state next time ...

state {
    key1: newVal1

    //But for key2 I want to keep the value as the same oldArray1
    //Now since that oldArray1 is not anywhere except in the old state, can I do this...?

    key2: state.key2
    .
    .
    .
}

So, if I do key2: state.key2and state.key2- an array, will the link be lost because the state is changed and state.key2 will not point to anything?

I just need a rough explanation of how links object/arraywill affect state in redux.

+4
source share
2 answers

, . , ,

export default  function(state = {}, action) {
switch(action.type) {
    case WHATEVER_ACTION:
         const newValue = action.payload.value; //assuming this comes from action
         return { ...state, key: newValue };
  }
}

, , , , , , , newState.

+3

, Redux , - , , , , Object.assign .

      switch (action.type) {
        case SET_VISIBILITY_FILTER:
          return Object.assign({}, state, {
            key1: action.newVal1,
            key2: state.key1,
          })
+1

Source: https://habr.com/ru/post/1682452/


All Articles