How to update single value inside specific array i

2019-01-07 05:14发布

I have an issue where re-rendering of state causes ui issues and was suggested to only update specific value inside my reducer to reduce amount of re-rendering on a page.

this is example of my state

{
 name: "some name",
 subtitle: "some subtitle",
 contents: [
   {title: "some title", text: "some text"},
   {title: "some other title", text: "some other text"}
 ]
}

and I am currently updating it like this

case 'SOME_ACTION':
   return { ...state, contents: action.payload }

where action.payload is a whole array containing new values. But now I actually just need to update text of second item in contents array, and something like this doesn't work

case 'SOME_ACTION':
   return { ...state, contents[1].text: action.payload }

where action.payload is now a text I need for update.

3条回答
三岁会撩人
2楼-- · 2019-01-07 05:42

You don't have to do everything in one line:

case 'SOME_ACTION':
  const newState = { ...state };
  newState.contents = 
    [
      newState.contents[0],
      {title: newState.contnets[1].title, text: action.payload}
    ];
  return newState
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-07 05:50

You can use map. Here is an example implementation:

case 'SOME_ACTION':
   return { 
       ...state, 
       contents: state.contents.map(
           (content, i) => i === 1 ? {...content, text: action.payload}
                                   : content
       )
    }
查看更多
不美不萌又怎样
4楼-- · 2019-01-07 06:00

You could use the React Immutability helpers

import update from 'react-addons-update';

// ...    

case 'SOME_ACTION':
  return update(state, { 
    contents: { 
      1: {
        text: {$set: action.payload}
      }
    }
  });

Although I would imagine you'd probably be doing something more like this?

case 'SOME_ACTION':
  return update(state, { 
    contents: { 
      [action.id]: {
        text: {$set: action.payload}
      }
    }
  });
查看更多
登录 后发表回答