在React中通过循环改变useState()的内容

huangapple go评论115阅读模式
英文:

Changing useState() content by loops in react

问题

我在React中声明了一个状态,像这样:

  1. const [properties, setProperties] = useState<any[]>([]);

它接收对象数组。我可以通过以下方式访问状态中数组的属性:

  1. properties.forEach((element: any) => {
  2. console.log(element.propertyId);
  3. });

它会显示属性的值。

问题是,我无法通过循环使用"setProperties"来更改值:

  1. for (var i = 0; i < properties.length; i++) {
  2. setProperties[i]({ ...properties, propertyId: "newValue" });
  3. }

感谢您的帮助。

英文:

I have declared a state in react like this:

  1. const [properties,setProperties]=useState&lt;any[]&gt;([]);

and it receives arrays of objects. I can access the arrays attributes of the state in this way:

  1. properties.forEach((element:any) =&gt; {
  2. console.log(element.propertyId)
  3. });

and it displays the values.

The problem is that I can not change the values by using "setProperties" through loops:

  1. for(var i=0;i&lt;properties.length;i++)
  2. {
  3. setProperties[i]({...properties,propertyId:&quot;newValue&quot;})
  4. }

I appreciate your helps

答案1

得分: 2

有几种方法可以实现这个,都涉及到只调用一次setState并传入新的状态数组。还要注意我们如何使用.map(...)来创建旧数组的副本。这对于向React表明状态已更改非常重要。

  1. 创建状态的副本,并使用副本调用setState一次。

    1. const newState = properties.map((element) => ({ ...element, propertyId: "newValue" }));
    2. setProperties(newState);
  2. 使用回调函数的方式设置属性:

    1. setProperties((oldProperties) => {
    2. return oldProperties.map((element) => ({ ...element, propertyId: "newValue" }));
    3. });
英文:

There are a couple ways you can do this, all of which involve calling setState only once with the new state array. Also note how we use .map(...) to create a copy of the old array. This is very important to signal to react that the state changed.

  1. Create a copy of your state and use that to call setState only once.

    1. const newState = properties.map((element) =&gt; ({ ...element, propertyId: &quot;newValue&quot; }));
    2. setProperties(newState);
  2. Use the callback style to set the properties:

    1. setProperties((oldProperties) =&gt; {
    2. return oldProperties.map((element) =&gt; ({ ...element, propertyId: &quot;newValue&quot; }));
    3. });

huangapple
  • 本文由 发表于 2023年8月9日 03:07:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定