這是我的 React 狀態:
const [questionList, setQuestionList] = useState([
{
_type: "radio",
answer: "",
point: "",
question: "",
options: ["A", "B"],
},
]);
當陣列有很多物件時,要更新一個物件,我像這樣編碼并且現在作業正常:
<textarea
rows="2"
value={questionList[number].question}
onChange={(e) => {
let a = questionList[number];
a.question = e.target.value;
setQuestionList([
...questionList.slice(0, number),
a,
...questionList.slice(number 1),
]);
}}
></textarea>
有沒有辦法使變數成為setState 中的宣告,我的意思是這 2 行:
let a = questionList[number];
a.question = e.target.value;
編輯:對不起,我忘記了。號值是陣列中的物體的位置。
uj5u.com熱心網友回復:
您可以先復制問題,改變陣列并將其設定為新狀態而不進行切片。
<textarea
rows="2"
value={questionList[number].question}
onChange={(e) => {
const copy = [...questionList];
copy[number].question = e.target.value;
setQuestionList(copy);
}}
/>
uj5u.com熱心網友回復:
我不知道下面的代碼是否可行,但請試一試。
const [questionList, setQuestionList] = useState([
{
_type: "radio",
answer: "",
point: "",
question: "",
options: ["A", "B"],
},
]);
When the array has many objects, to update an object I code like this and it works fine now:
<textarea
rows="2"
value={questionList[number].question}
onChange={(e) => {
setQuestionList([
...questionList.slice(0, number),
{...questionList[number], question: e.target.value}
...questionList.slice(number 1),
]);
}}
></textarea>
uj5u.com熱心網友回復:
像這樣的東西
setQuestionList(prev => {
prev[number].question = e.target.value;
return [...prev];
});
uj5u.com熱心網友回復:
我建議你看看useReducer為物件型別的狀態管理值創建的鉤子。
使用減速機
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365783.html
標籤:javascript 反应
上一篇:關于反應鉤子的切換不起作用
