![](/img/trans.png)
[英]ReactJS error TypeError: Cannot convert undefined or null to object
[英]Cannot convert undefined or null to object reactjs
我想知道如果替換狀態數組中已經存在的項目,我得到了一個很好的解決方案
https://codesandbox.io/s/4xl24j7r69
它工作正常,但我的問題是,如果該項目在數組中不存在,則無法添加新項目我收到錯誤Cannot convert undefined or null to object
像這樣:
add = () => {
let newUser1 = {
"userId": 1,
"id": 3, // this is new id which is doesn't exist in this.state.data
"title": "Two New",
"body": "new data"
}
this.setState(prevState => {
let newData = prevState.data;
let user = newData.find(d => d.id === newUser1.id);
Object.assign(user, newUser1);
return { data: newData };
})
};
您沒有將newUser添加到data on狀態。
add = () => {
let newUser1 = {
"userId": 1,
"id": 4,
"title": "Two New",
"body": "new data"
}
this.setState(prevState => {
const user = prevState.data.find(d => d.id === newUser1.id);
if (!!user) {
//Casting user to a boolean, if find did return a truthy value you add it to the data with map
Object.assign(user, newUser);
const newData = prevState.data.map(d => d.id === user.id ? user : d);
return { data: newData }
} else {
return { data: prevState.data.concat(newUser1)};
}
})
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.