[英]TypeError: Object.key is read-only
伙計們。 我正在嘗試在我的發票應用程序上實現編輯功能,我將發票作為道具傳遞以形成 state,如下所示:
const EditInvoice = ({invoice}) => {
const [formInputs, setFormInputs] = useState([
]);
const [form,setForm] = useState({
clientCity : invoice.clientAddress.city,
clientCountry : invoice.clientAddress.country,
clientPostCode : invoice.clientAddress.postCode,
clientStreet : invoice.clientAddress.street,
clientEmail : invoice.clientEmail,
clientName : invoice.clientName,
createdAt : invoice.createdAt,
description : invoice.description,
id : invoice.id,
items: formInputs,
paymentDue : invoice.paymentDue,
paymentTerms : invoice.paymentTerms,
senderCity : invoice.senderAddress.city,
senderCountry : invoice.senderAddress.country,
senderPostCode : invoice.senderAddress.postCode,
senderStreet : invoice.senderAddress.street,
status : invoice.status,
total : invoice.total
})
此時一切正常,handleChange function 適用於除 formInputs 之外的所有內容,我嘗試像這樣設置 formInputs state const [formInputs, setFormInputs] = useState([...invoice.items]);
並使用 useEffect,如下所示:
useEffect(() =>{
setFormInputs([...invoice.items])
},[])
他們都填充了這些字段,但是如果我嘗試更新我的發票項目數組,我會收到只讀類型錯誤,以防萬一,這就是我用於我的 handleChange function
const handleItemChange = (index,e) =>{
const values = [...formInputs]
values[index][e.target.name] = e.target.value;
values[index].total = (values[index].price * values[index].quantity).toFixed(2);
setFormInputs(values)
}
希望各位大神給個解決辦法,先謝謝了!
我不知道這是否是一種 hacky 方式,但這個解決方案似乎有效。
useEffect(() =>{
invoice.items.map(item => setFormInputs(prevState => ([...prevState, {
id : item.id,
name : item.name,
quantity : item.quantity,
price : item.price,
total : item.total
}])))
console.log(formInputs);
},[])
您的代碼中的問題是您正在嘗試重新分配一個只讀的const
值(它會阻止重新分配)。 將您的值定義為let
。
所以而不是
const values
你應該把它定義為
let values
由於state
可能會異步更新,因此您不應依賴它們的值來計算下一個 state。
像這樣改變方法:
const handleItemChange = (index,e) =>{
setFormInputs(prevValues => {
const newValues = [ ...prevValues];
newValues[index][e.target.name] = e.target.value;
newValues[index].total = (values[index].price * values[index].quantity).toFixed(2);
return newValues;
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.