简体   繁体   中英

react-native redux nested array reducer

I am learning to write reducers for arrays. For example, one of the reducers changes array elements from integers to arrays.

Original state:

[0, 3, 5, 3, 9, 8]

Action:

case ADD_NEST:
      return state.map(i => [i, action.payload]);

New state:

[[0, 0], [3, 0], [5, 0], [3, 0], [9, 0], [8, 0]]

I'm trying to write a reducer that would change the second element of sub-arrays based on the condition of the first one. ( eg, if the first element of the subarray is greater than 3 , change the second element to 1 ).

[[0, 0], [3, 0], [5, 1], [3, 0], [9, 1], [8, 1]]

so far I have ( not much as I'm stuck ):

case SET_BIT:
      return state.map(i => (i[0] > 3 ? ??? : i));

Thank you for advice!

Like this?

case SET_BIT:
  return state.map(i => (i[0] > 3 ? [i[0], i[1] + 1] : i));

Although, that's a bit weird/dangerous. What happens if SET_BIT gets dispatched when your state of that reducer is still a flat array? Then the above code will crash. Then you would have to do something like:

case SET_BIT:
  return state.map(i => (
    Array.isArray(i) && i[0] > 3
      ? [i[0], i[1] + 1]
      : i
  ));

I don't know the details of what you are trying to do here, but generally speaking I think it's best to keep the structure of the state of a reducer consistent. I tend to avoid nested structures in the state of my redux store because I try to keep the state of my redux store as normalized as I can. That makes reducers a lot easier to maintain. If I need to nest stuff for my views I usually do that in the selectors.

But again, I lack context, so not sure if any of this advice is relevant to you. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM