gpt4 book ai didi

javascript - reactJS 对象状态数组 - 我如何在 setState() 中引用状态数组对象

转载 作者:行者123 更新时间:2023-11-30 20:14:46 25 4
gpt4 key购买 nike

我有以下声明:

    constructor(props) {
super(props);
this.state = {
productArray: [{
barcode: '',
name: ''
}],
numberOfRecords: '',
return_code: '',
return_string: ''
};
}

我希望像这样引用状态字段:

this.state.productArray[0].barcode and this.state.productArray[1]

我还有一段代码尝试更新状态。代码如下所示:

for (counter=0;counter<numberOfRecords;counter++) {

currentComponent.setState({productArray[counter].barcode: tempData.barcode[counter]});
currentComponent.setState({productArray[counter].name: tempData.name[counter]});
}

这不会编译,错误指向第一个 setState 命令。编译器指向对 productArray[counter].barcode 的引用中的 [ 表示它需要一个 ','。

我是否正确定义了状态?如果不是,正确的语法是什么?如果是,引用各个状态字段片段的正确语法是什么?

最佳答案

理想情况下,您只需要调用一次setState,您可以做的是创建一个临时变量来存储计算,例如

const { productArray, numberOfRecords } = this.state;
const newProducts = [ ... productArray ];
for( let counter = 0; counter < numberOfRecords; counter ) {
const item = newProducts[ counter];
newProducts[ counter] = { ...item, barcode: 'value' },
}

this.setState({ productArray: newProducts });

通过使用扩展运算符...,您可以创建shallow copies对象和数组。

关于javascript - reactJS 对象状态数组 - 我如何在 setState() 中引用状态数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com