我有以下表/陣列:

如果我按下藍色按鈕,則與記錄具有相同組的所有專案都應更改狀態(免費)。但現在它只是改變記錄的值和它上面的所有專案。例如,如果我按下第 1 號記錄上的按鈕,那么它本身和以上所有(第 0 號)都會更改狀態(免費)。
以下代碼用于遍歷陣列并更改狀態:
private _updateFreeStatus = (record: QuestionModel): void => {
fetch('api/Test/UpdateGratisStatus', {
headers: { 'Content-Type': 'application/json' },
method: 'PUT',
body: JSON.stringify({
'group': record.group,
'free': record.free,
})
});
this.state.question.map(item => {
if (item.group === record.group)
{
item.free = !record.free;
}
});
}
uj5u.com熱心網友回復:
- 不要改變狀態
- 創建一個副本,并使用
setState
利用
const updatedQuestions = this.state.question.map(item => {
if (item.group === record.group) {
return {
...item,
free: !record.free
}
}
return item;
});
this.setState({question: updatedQuestions});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383211.html
標籤:javascript 数组 反应 打字稿
