简体   繁体   English

吊具分配新值时出现问题

[英]Problem with spreader in assigning new values

I'm am attempting to assign a new value based on a passed in index variable and it isn't updating in my state. 我正在尝试根据传入的索引变量分配一个新值,并且在我的状态下它没有更新。 Its intended to toggle an object array which will allow for conditional rendering but as I do a console log of my state it is not changing. 它的意图是切换对象阵列,以允许条件渲染,但是当我执行状态控制台日志时,它没有改变。

this.state = {
      value: 0,
      metadata: MetaDataData,
      togglePanel: false,
      activeItem: {0: false, 1: false, 2: false}
    };

toggleActiveItem = (activeIndex) => {
    const index = activeIndex
    this.setState((prevState) => {
      return {...prevState.activeItem, [index]: !prevState.activeItem[index]}
    })
  }

For instance when this is called with a passed in index of zero I would expect that the 0th instance to be changed from false to true. 例如,当传入索引为零调用此方法时,我希望第0个实例从false更改为true。

It is not working because you are not referring to the object 它不起作用,因为您未引用该对象

activeItem: {0: false, 1: false, 2: false}

By doing spread you update activeItem, but you are not setting it in the current state 通过传播,您可以更新activeItem,但未将其设置为当前状态

Try this: 尝试这个:

this.state = {
      value: 0,
      metadata: MetaDataData,
      togglePanel: false,
      activeItem: {0: false, 1: false, 2: false}
    };

toggleActiveItem = (activeIndex) => {
    const index = activeIndex
    this.setState((prevState) => {
      const newState = {...prevState.activeItem, [index]: !prevState.activeItem[index]}
      return {activeItem: newState}
    })
  }

So I figured out my issue. 所以我想出了我的问题。 I wasn't actually assigning these values to the state object activeItem. 我实际上并没有将这些值分配给状态对象activeItem。

The return needs to be: 回报必须是:

return {activeItem: {...prevState.activeItem, [index]:!prevState.activeItem[index]}}

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

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