Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React-使用setState函数调用删除嵌套数组项_Reactjs_Filter_Setstate - Fatal编程技术网

Reactjs React-使用setState函数调用删除嵌套数组项

Reactjs React-使用setState函数调用删除嵌套数组项,reactjs,filter,setstate,Reactjs,Filter,Setstate,我试图使用setState从数组中删除一个(半)深度嵌套项,但它似乎不起作用。我的州结构如下: state = { currentSeries: null, currentRowIndex: null, rows: [ { id: shortid.generate(), nodes: [], series: [], // array with item I want to remove }, ], }; 和我的删除项目呼叫:

我试图使用setState从数组中删除一个(半)深度嵌套项,但它似乎不起作用。我的州结构如下:

state = {
  currentSeries: null,
  currentRowIndex: null,
  rows: [
    {
      id: shortid.generate(),
      nodes: [], 
      series: [], // array with item I want to remove
    },
  ],
};
和我的删除项目呼叫:

onRemoveModelElementClick = (rowId, modelElementId) => {
  this.setState((prevState) => {
    const index = prevState.rows.findIndex(x => x.id === rowId);
    const series = prevState.rows[index].series.filter(s => s.id !== modelElementId);
    return series;
  });
};

我尝试了几种方法来传播剩余状态,但它似乎没有正确更新。我知道rowId和modelementid是正确的,我可以验证它们是否筛选出了正确的项。我只是不知道该归还什么。我知道这很简单,但就我个人而言,我看不到

我的建议是使用它使事情更容易消化。然后你可以这样写:

onRemoveModelElementClick = (rowId, modelElementId) => {
  const updatedRowsState = this.state.rows.map(row => {
    // this is not the row you're looking for so return the original row
    if (row.id !== rowId) {
      return row;
    }

    const filteredSeries = row.series.filter(s => s.id !== modelElementId);
    return {
      // spread properties (id, node, series)
      ...row,
      // overwrite series with item filtered out
      series: filteredSeries,
    };
  });

  // since rest of the state doesn't change, we only need to update rows property
  this.setState('rows', updatedRowsState);
}

希望这有帮助,如果您有任何问题,请告诉我。

我认为这里的问题是您的代码如何使用
setState
setState
函数必须返回一个对象。假设筛选函数如您所述正确,则返回一个对象以更新状态:

return { series };

以下是我如何让它工作,以防它能帮助其他人:

onRemoveModelElementClick = (rowId, modelElementId) => {
  this.setState((prevState) => {
    const updatedRowState = prevState.rows.map((row) => {
      if (row.id !== rowId) {
        return row;
      }

      const filteredSeries = row.series.filter(s => s.id !== modelElementId);
      return {
        ...row,
        series: filteredSeries,
      };
    });
    return {
      rows: updatedRowState,
    };
  });
};

这一切都归功于Dom的伟大思想和逻辑

这是个好主意。你写的东西不是现成的,但它让我找到了解决办法,所以我接受了。我将为我所做的工作添加一个答案。