英文:
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<any[]>([]);
and it receives arrays of objects. I can access the arrays attributes of the state in this way:
properties.forEach((element:any) => {
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<properties.length;i++)
{
setProperties[i]({...properties,propertyId:"newValue"})
}
I appreciate your helps
答案1
得分: 2
有几种方法可以实现这个,都涉及到只调用一次setState
并传入新的状态数组。还要注意我们如何使用.map(...)
来创建旧数组的副本。这对于向React表明状态已更改非常重要。
-
创建状态的副本,并使用副本调用
setState
一次。const newState = properties.map((element) => ({ ...element, propertyId: "newValue" })); setProperties(newState);
-
使用回调函数的方式设置属性:
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.
-
Create a copy of your state and use that to call
setState
only once.const newState = properties.map((element) => ({ ...element, propertyId: "newValue" })); setProperties(newState);
-
Use the callback style to set the properties:
setProperties((oldProperties) => { return oldProperties.map((element) => ({ ...element, propertyId: "newValue" })); });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论