![](/img/trans.png)
[英]setstate object:{array:[]} in reactjs how could i add the **key and value inside the array which is in the state object**?
[英]reactJS state array of objects - how do I reference the state array object in setState()
我有以下聲明:
constructor(props) {
super(props);
this.state = {
productArray: [{
barcode: '',
name: ''
}],
numberOfRecords: '',
return_code: '',
return_string: ''
};
}
我希望像這樣引用狀態字段:
this.state.productArray[0].barcode 和 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 });
通過使用擴展運算符...
您可以創建對象和數組的淺拷貝。
你不能直接改變狀態,請這樣做
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 數組的特定部分
和
我可以從 state 中刪除 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.