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

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

Changing useState() content by loops in react

问题

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

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

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

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

它会显示属性的值。

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

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

感谢您的帮助。

英文:

I have declared a state in react like this:

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:

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

and it displays the values.

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

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

I appreciate your helps

答案1

得分: 2

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

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

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

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

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.

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

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

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:

确定