React - remove nested array item using setState function call

后端 未结 3 522
再見小時候
再見小時候 2021-01-27 06:39

I am trying to remove a (semi) deeply nested item from an array using setState but it doesn\'t seem to be working. My state is structured as follows:

state = {
         


        
3条回答
  •  迷失自我
    2021-01-27 07:03

    Here is what I did to get it working in case it can help someone else:

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

    All credit to Dom for the great idea and logic!

提交回复
热议问题