如何将数组数据推送到对象上?

时间:2020-10-02 00:21:43

标签: reactjs

我正在尝试将newState数据添加到databaseChanges数据的末尾。但是我收到此错误:

TypeError:散布不可迭代实例的无效尝试

export default connect(mapStateToProps, mapDispatch)(HomeScreen);

const addToProduction = ({target}, {id, databases}) => {
  const databaseChanges = props.unitTestsData.map((test) => {
    return {
      unit_test_id: test.id,
      databases: test.databases,
    };
  });

  setDatabaseArr((previousState) => {
    let newState = [...previousState];
    if (target.checked) {
      newState = [...newState, {unit_test_id: id, databases}];
    } else {
      const i = newState.findIndex(({unit_test_id}) => unit_test_id === id);
      if (i !== -1) newState.splice(i, 1);
    }
    return databaseChanges.push(newState);
  });
};

return (
  <div>
    <Checkbox
      mainColor
      changeHandler={(e) => addToProduction(e, test)}
      data={{}}
      id={test.id.toString()}
    />
  </div>
);

1 个答案:

答案 0 :(得分:0)

可能“ previousState”的初始状态不是[],而是类似null''