如何将状态附加到数组

时间:2020-10-07 04:00:21

标签: reactjs

我试图将props.addremoveDatabase状态变量(来自其他组件,为什么使用props)附加到newState数组的末尾。但是,这是行不通的,我不确定为什么要尝试使用push方法这样做。

错误:

enter image description here

const [addRemoveDatabase, setAddRemoveDatabase] = useState([
  'iadcaprod.auiag.corp/iadpprod',
]);
const [productionDatabaseData, setProductionDatabaseData] = useState([]);
const addToProduction = ({target}, {id, databases}) => {
  setProductionDatabaseData((previousState) => {
    let newState = [...previousState];
    if (target.checked) {
      newState = [
        ...newState,
        {unit_test_id: id, databases: databases.push(props.addRemoveDatabase)},
      ];
    } else {
      const i = newState.findIndex(({unit_test_id}) => unit_test_id === id);
      if (i !== -1) newState.splice(i, 1);
    }

    return newState;
  });
};

错误: enter image description here

1 个答案:

答案 0 :(得分:1)

嗯,您使用对象。对吧?

databases.push(props.addRemoveDatabase)
newState = [
  ...newState,
  {unit_test_id: id, databases: [...databases]},
];