如何使用带有多个数组的对象的钩子设置setState?如何在这里设置债务人?

时间:2019-07-15 06:25:18

标签: javascript reactjs react-hooks

我要删除数组中的一个id,在此处过滤后如何设置setState?

https://codesandbox.io/s/react-example-1m2qn

 const Debtors = () => {
      const debtors = [
        {
          id: 1,
          name: "John",
          relation: "friend",
          statement: [
            { id: 1, date: 2010, amount: "1000", purpose: "John" },
            { id: 2, date: 2014, amount: "2000", purpose: "john" }
          ]
        },   
,
    {
      id: 2,
      name: "Jack",
      relation: "Friend",
      statement: [
        { id: 1, date: 2010, amount: "1000", purpose: "jack" },
        { id: 2, date: 2014, amount: "2000", purpose: "jack" }
      ]
    }  


      ];


  const [newDebtors, setdebtors] = React.useState(debtors);

  const handleDelete = (stat, i) => {
    const newList = newDebtors[0].statement.filter(x => x.id !== stat.id);

// How to set debtors here ?
   // setdebtors({ ...newDebtors, statement[0]: newList }); 
  console.log(newList)

//如何在这里设置债务人?

4 个答案:

答案 0 :(得分:1)

有两个问题:

1)您正在迭代渲染中的原始债务人对象,而不是通过newDebtors创建的useState()状态,这就是UI似乎没有变化的原因。

您需要:newDebtors[0].statement.map

2)您需要在handleDelete()中传递项目索引,以便它知道要更新数组中的哪个项目。您可以让函数执行以下操作:

在onClick中:

 <a
   href="javascript:;"
   onClick={() => handleDelete(stat, i, 0)}
 >

在handleDelete()中:

  const handleDelete = (stat, i, arrayIndex) => {
    const updatedDebtors = newDebtors.map((item, index) => {
      if (index === arrayIndex) {
        return {
          ...item,
          statement: item.statement.filter(
            statement => statement.id !== stat.id
          )
        };
      } else {
        return item;
      }
    });

    setDebtors(updatedDebtors);
  };

请参阅沙盒以获取完整解决方案:https://codesandbox.io/s/react-example-x7uoh

答案 1 :(得分:0)

您应该这样做:

setdebtors((prevState) => {
  let newArray = Array.from(prevState);    // Copy the array
  // Manipulate the array as you wish
  return newArray;                         // return it
});

答案 2 :(得分:0)

问题是您正在突变“债务人”数组,您需要映射整个债务人数组并更改对象中的任何属性。

const handleDelete = (stat, i) => {
const newList = newDebtors.map((debtor, i) => {
  if (i === 0) {
    debtor.statement = debtor.statement.filter(x => x.id !== stat.id);
  }
  return debtor;
});
setdebtors(newList);};

一种更好的方法是使用“ useReducer”,该“ useReducer”用于突变更复杂的状态,如您在此处所示。文档非常有用useReducer

答案 3 :(得分:0)

嗯,我不知道你到底想做什么, 这是您要找的吗?

const handleDelete = (stat, i) => {
    const newList = newDebtors[0].statement.filter(x => x.id !== stat.id);
    const newFirstItem = {...newDebtors[0],statement: newList}
    const newDebtorList = newDebtors.filter(x => x.id !== newFirstItem.id);
    newDebtorList.unshift(newFirstItem);
    setdebtors(newDebtorList); 
}

我知道这似乎很复杂,但是您实际上需要执行此操作,因为您无法在状态下更改数组... 我在这里所做的是,首先创建一个新的语句列表(newList),然后创建一个newFirstItem设置为新的newDebtors [0],然后创建一个除第一个元素外的所有newDebtors元素的新数组(newDebtorList),我通过将newFirstItem推到第0个位置(使用unshift)修改了此数组 终于用这个新数组更新了状态... 希望对您有帮助:)

注意:这是用于更改第0个元素(如果您具有ID),请相应地更改代码