简体   繁体   English

React:在状态下,我将如何在某个索引处更新嵌套对象?

[英]React: In state, how would I update a nested object at a certain index?

How would I update values of single events using setState? 如何使用setState更新单个事件的值? Also happy to see how it's done outside React. 也很高兴看到它在React之外如何完成。

state = {events: [{
  event1:{
    name: 'Name 1',
    id: 1,
  },
},{
  event2:{
    name: 'Name 2',
    id: 2,
  },
},{
  event3:{
    name: 'Name 3',
    id: 3,
  },
}]}

You can do it using Array.map method: 您可以使用Array.map方法执行此操作:

renameEvent(idToRename, newName) {
  this.setState(prevState => ({
    events: prevState.events.map(event => {
      if (event.id === idToRename) {
        return {...event, name: newName};
      } else {
        return event;
      }
    });
  })); 
}

for current structure only Array.map can help. 对于当前结构,只有Array.map可以提供帮助。 But I can see id field inside. 但是我可以看到里面的id字段。 So how about changing structure to having object? 那么如何将结构更改为具有对象呢?

{
 1: {
   event1:{
    name: 'Name 1',
    id: 1,
   },
  },
 2: {
   event2:{
    name: 'Name 2',
    id: 2,
   },
 },

Then you would get power of spread operator: 然后,您将获得散布算子的功能:

this.setState(prevState => ({
    ...prevState.events,
    [idToReplace]: {
        ...prevState.events[idToReplace],
        name: 'new name',
    },
}));

Also I wondering if it make sense to have so deep nesting in single element. 我也想知道在单个元素中进行如此深层的嵌套是否有意义。 Maybe it'd better to deal with name of specific event inside of child component. 也许最好在子组件内部处理特定event name

As @Oleksandr Kovpashko mentioned you can use .map since it creates a new array. 正如@Oleksandr Kovpashko提到的,您可以使用.map因为它会创建一个新数组。

You can also use .slice() to clone the array and then mutate it. 您还可以使用.slice()克隆数组,然后对其进行突变。 Note that it only clones the array, not the items. 请注意,它仅克隆数组,而不克隆项目。 You should NOT mutate items: 您不应该更改项目:

const arr = ['one','two','three','three','five'];
const clone = arr.slice()

clone[3] = 'four';

console.log(clone);

Since your top-level state property ( events ) is an array, you can manipulate the value and call setState({ events: yourUpdatedEventsArray }) . 由于您的顶级状态属性( events )是一个数组,因此您可以操纵该值并调用setState({ events: yourUpdatedEventsArray })

Because setState is asynchronous, you will want to do this using the setState callback: 由于setState是异步的,因此您将需要使用setState回调来执行此操作:

setState(prevState => {
  const updatedEvents = prevState.events.map(event => {
    # update and return `event` as needed
  })

  return { events: updatedEvents }
})

If you weren't passing this back to React, you could modify the array in place using findIndex and then array[index].name = "foo" , but you don't want to mutate the state directly with React. 如果您没有将其传递回React,则可以使用findIndex修改数组,然后使用array[index].name = "foo" ,但是您不想直接使用React改变state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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