简体   繁体   English

在React中动态添加属性到this.state

[英]Dynamically add properties to this.state in React

I'm running a map that dynamically creates a group of components where the total number is based on the length of an array. 我正在运行一个映射,该映射可动态创建一组组件,其中组件的总数基于数组的长度。 Each component needs its own value in state. 每个组件都需要有自己的状态值。

So if the map runs over an array of three items... 因此,如果地图在三个项目的数组上运行...

arr.map((item, index) => {
  const newStateProp = "item" + index;
  return newStateProp;
}

The app state would look like this somewhere...maybe similar to what you would see in React Dev Tools... 应用程序状态看起来像这样……可能类似于您在React Dev Tools中看到的样子……

...
this.state: {
  item0: false,
  item1: false,
  item2: false
}
...

Not sure if this is doable...thanks in advance. 不知道这是否可行...在此先感谢。

You could do something like this 你可以做这样的事情

newState = {};

for (let i = 0; i < arr.length; i++) {
    newState[arr[i]] = false
}

setState(newState);

Is that what you're trying to do? 那是你想做的吗?

Yeah, It is possible to do like that. 是的,可以那样做。

If you want to do something like that after component is mounted, you can refer to Chris Sandvik Answer . 如果要在安装component后执行类似的操作,可以参考Chris Sandvik Answer

But If you want to do it in constructor using from props or anything else. 但是如果您想使用props或其他任何东西在构造函数中执行此操作。 You can do some change to his code like below. 您可以对他的代码做一些更改,如下所示。

 const arr = []; const newState = {}; for (let i = 0; i < arr.length; i++) { newState[`item${arr[i]}`] = false; } this.state = newState; console.log('State', this.state); 

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

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