簡體   English   中英

突變嵌套對象

[英]Mutating nested object

我試圖在將對象設置為這樣的狀態之前不使其內部發生變化:

isDraggable = () => {
        let steps = [...this.state.stepsData];

        steps = steps.map(step => {
            return {
                ...step,
                dataGrid.static: !step.dataGrid.static 
            }
        });

        this.setState({stepsData: steps})
 };

對象結構如下所示:

{
 stepsData:[{
  dataGrid: {
   x: ...
   y: ...
   static: true
  }
 }]
}

這行dataGrid.static: !step.dataGrid.static不編譯dataGrid.static: !step.dataGrid.static 我該如何解決? 提前致謝!

您需要克隆dataGrid引用的對象。 另請注意, 基於狀態設置狀態時必須使用setState的函數回調版本

isDraggable = () => {
    this.setState(prevState => {
        return {stepsData: prevState.steps.map(step => {
            return {
                ...step,
                dataGrid: {...step.dataGrid, static: !step.dataGrid.static}
            };
        })};
    });
};

或更簡潔,但也許不太清楚:

isDraggable = () => {
    this.setState(prevState => ({
        stepsData: prevState.steps.map(step => ({
            ...step,
            dataGrid: {...step.dataGrid, static: !step.dataGrid.static}
        }))
    }));
};

您可以覆蓋dataGrid鍵並擴展step.dataGrid

isDraggable = () => {
    this.setState(prevState => {

        const steps = prevState.stepsData.map(step => {
            return {
                ...step,
                dataGrid: {
                    ...step.dataGrid,
                    static: !step.dataGrid.static
                }
            }
        });

        return { stepsData: steps };
    })
};

不幸的是,您必須取消嵌套要更改的對象的每一層,例如:

isDraggable = () => {
  this.setState(state => {
    return state.stepsData.map(step => {
      const { dataGrid } = step;

      return {
        ...step,
        dataGrid: {
          ...dataGrid,
          static: !dataGrid.static
        }
      };
    });
  });
};

編輯 :將setState更改為其功能回調形式,以響應TJ Crowder的評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM