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



我有以下声明:

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 });

通过使用 spread 运算符...可以创建对象和数组的浅表副本。

你不能直接改变状态,请这样做

let tempvar = this.state.productArray;
for (counter=0;counter<numberOfRecords;counter++) {
tempvar[counter].barcode= newValue
}
this.setState({productArray:tempvar})

更新对象嵌套数组的推荐方法是利用Object.assign的强大功能。请记住,Object.assign 不会执行深度克隆,因为它只复制属性值,

this.setState({
productArray:  Object.assign({}, this.state.productArray[0], {
barcode: 'any value',
})}, ()=>{
console.log(this.state)
}
);

在您的情况下,这就是您可以使用速记符号实现此目的的方法:

for (var counter = 0; counter < 1; counter++) {
this.setState({
productArray:  Object.assign({}, this.state.productArray[counter], {
barcode: tempData.barcode[counter],
name: tempData.name[counter]
})}, ()=>{
console.log(this.state)
}
);
}

至于数据,我正在挑选 tempData 数组的特定部分

我可以从状态中删除 numberOfRecords 并从 tempData.length 获取它。

好的,所以productArray包含tempData中的对象的属性子集,而不是项的子集。

然后我什至懒得尝试复制值并简单地映射新值。

currentComponent.setState({ 
productArray: tempData.map(item => {
const {barcode, name} = item;
return {barcode, name};
})
});
//or in short
currentComponent.setState({ 
productArray: tempData.map(({barcode, name}) => ({barcode, name}))
});

回答您的问题;如果你想访问和更新一些嵌套属性,你应该在setState()中使用一个更新函数,以便在代码尝试修改它之前,所有以前的更新都已应用于this.state

像这样:

currentComponent.setState((state) => {
for(let i = 0; i<tempData.length; ++i){
let from = tempData[i], to = state.productArray[i];
to.name = from.name;
to.barcode = from.barcode;
}
return state;
});

这种方法的缺点/缺陷是,它不能处理tempData.length !== state.productArray.length的情况。

最新更新