我正在嘗試更改嵌套在陣列中的物件欄位的值。我不斷收到此錯誤,“無法分配給物件'[object Array]'的只讀屬性'0'”
這是狀態的樣子
{
"school stuffs": [
{
"_id": "629332e33f0e48af3d626645",
"completed": false,
},
{
"_id": "629425fc9c50b142dff947a9",
"completed": true,
}
],
"household and furniture": [
{
"_id": "629334424709234a344c0189",
"completed": false,
},
{
"_id": "629334f12da7859af0828c9a",
"completed": false,
}
]
}
這是我用來改變狀態并將“完成”的值更改為當前布林值的相反值的代碼。
const newArray = { ...productArray, [value]: {...productArray}[value] }
const index = productArray[value].findIndex(index => index._id === innerElement._id)
newArray[value][index].completed = !newArray[value][index].completed
console.log(newArray[value][index].completed);
uj5u.com熱心網友回復:
react 的問題是,你不應該改變狀態,為此存在 useState 和純函式方法,就像在下一個例子中一樣:想象你有一個購物車。
const [cart, setCart] = useState([]);
你想添加一個產品,你可以這樣做:
const addCart = product => {
setCart([...cart, product]) // Using destructuring
setCart(cart.concat(product)) // Using pure functions.
}
如果你想改變狀態內物件中的道具,你可以這樣做:
const increaseQuantity = id => {
const mappedCart = cart.map(prd => prd.id === id ? {...prd, quantity: prd.quantity 1} : prd);
setCart(mappedCart)
}
當然,您可以使用簡單的 for 回圈或其他方式,但這里的問題是您不能在 react 中改變狀態。
我希望我能幫助你
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483297.html
標籤:javascript 反应 反应钩子
上一篇:添加最后一個parseFloat時JavaScript'calculator'不提供'runningtotal'
