如果相同的鍵已經可用,我有一個函式可以獲取用戶輸入并更新陣列。在這篇文章的幫助下
這就是它的外觀;
const handleClickYes = (question) => {
// find if question is in the data array
const hasQuestion = data.find(({ parentId }) => question.id === parentId)
const indexOfQuestion = data.indexOf(hasQuestion)
if (hasQuestion) {
// update the value with specific selected index in the array.
data[indexOfQuestion] = { question: question.if_yes, parentId: question.id, userChoice: 'YES', child: [] }
} else {
setData((data) => data.concat({ question: question.if_yes, parentId: question.id, userChoice: 'YES', child: [] }))
}
localStorage.setItem('deviceReport', JSON.stringify(data))
}
我正在使用 localStorage 來保持狀態
const deviceReport = localStorage.getItem('deviceReport') ? JSON.parse(localStorage.getItem('deviceReport')) : []
const [data, setData] = useState(deviceReport)
這里的問題是如果我使用 setData 然后它會立即更新但是在這部分替換陣列
data[indexOfQuestion] = { question: question.if_yes, parentId: question.id, userChoice: 'YES', child: [] }
它不會更新 JSX 部分上的映射資料。如何配置它以在 setState 中更新它。? 或任何其他更好的選擇來更新陣列。
uj5u.com熱心網友回復:
你沒有在你的街區setState()的前半部分打電話。if另外,永遠不要直接改變 state。制作一個可變副本,如下所示:
const handleClickYes = (question) => {
// find if question is in the data array
const hasQuestion = data.find(({ parentId }) => question.id === parentId);
const indexOfQuestion = data.indexOf(hasQuestion);
// copy data to mutable object
let newData = [...data];
if (hasQuestion) {
// update the value with specific selected index in the array.
newData[indexOfQuestion] = {
question: question.if_yes,
parentId: question.id,
userChoice: "YES",
child: [],
};
} else {
// concat existing data with a new question
newData = [
...newData,
{
question: question.if_yes,
parentId: question.id,
userChoice: "YES",
child: [],
},
];
}
localStorage.setItem("deviceReport", JSON.stringify(newData));
setData(newData);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449296.html
標籤:javascript 数组 反应 指数
