[英]React setState does not update a state array value
我正在嘗試使用setState
更改state
組件中的 state 。
更具體地說,我有一張桌子,我想編輯/更新它的一個元素。 對於這種情況,我將數組中值的 position 的索引傳遞給handleTableFieldOnChange
function。
因為我知道我不應該改變 state,所以我使用了一個外部庫來深度復制表數組/列表。
深拷貝和新的賦值有效。 深拷貝也適用於JSON.parse(JSON.stringify(this.state.tables));
選擇。
問題:由於某種原因this.setState(...)
不會改變表的值。
我確實知道setState
是異步的,這就是我使用回調並在其中使用console.log(...)
來檢查更新值的原因。
console.log(...)
仍然發出舊值。
private handleTableFieldOnChange(val: boolean | string | number | [number, string], tblRowIndex: number, tblIndex: number, tblColINdex: number) {
const cloneDeep = require('lodash.clonedeep');
const newTables = cloneDeep(this.state.tables);
if (newTables && newTables[tblIndex] && newTables[tblIndex].items ) {
newTables[tblIndex].items![tblRowIndex][tblColINdex].value = val;
}
this.setState( {tables: newTables}, () => {
console.log(this.state.tables)
})
}
state: State = {
tables: [],
report: this.props.report,
};
constructor(props: DetailProp, state: State) {
super(props, state);
this.initFieldsAndTabels();
}
private initFieldsAndTabels() {
if (this.state.report && this.state.report.extraction_items) {
this.state.tables = [];
this.state.report.extraction_items.forEach((extractionItems) => {
this.state.tables.push(extractionItems);
});
}
}
handleTableFieldOnChange
中的代碼對我來說看起來不錯。
但是,在initFieldsAndTabels
中,您直接在 state 上應用push
,而不是調用可能導致問題的setState
:
this.state.report.extraction_items.forEach((extractionItems) => {
this.state.tables.push(extractionItems); //#HERE
});
同樣作為React.Component docs state 你不應該在構造函數中調用setState
(你在constructor
constructor
調用initFieldsAndTabels
。相反你可以使用componentDidMount
。
PS如果你想在構造函數中添加那些提取項,那么你需要這樣的東西:
constructor(props) {
super(props);
// method should return a new array/object, but not modify state
const tables = this.initFieldsAndTabels();
this.state = {
tables,
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.