无法将undefined或null转换为object reactjs

时间:2018-03-15 23:28:37

标签: javascript 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 };
    })
  };

1 个答案:

答案 0 :(得分:1)

您没有将newUser添加到状态数据中。

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)};
      }
    })
  };