React - remove nested array item using setState function call

后端 未结 3 519
再見小時候
再見小時候 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 06:54

    My recommendation would be to use .map to make things are bit easier to digest. You can then write it like so:

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

    Hope this helps and let me know if you have any questions.

    0 讨论(0)
  • 2021-01-27 06:57

    I think the issue here is how your code uses setState. The setState function must return an object. Assuming your filtering functions are correct as you describe, return an object to update the state:

    return { series };
    

    setState documentation

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题