首页 > 解决方案 > 为什么在使用 prevState 而不是简单的 setState 时需要进行深拷贝?

问题描述

您在下面看到的代码在我使用时可以正常工作,setState但是一旦使用prevState,它就会中断!,我不明白为什么,当然我知道如果我buttonList像这样复制对象:

const newButtonList = prevState.buttonList.map(item => {
  return {...item}
}

这将解决问题,但我仍然不明白为什么以前的解决方案不起作用!
这是完整的代码和沙盒链接: https
://codesandbox.io/s/goofy-christian-fb3ho?file=/src/Demo.js 代码:onClick1
有效,但 onClick2 无效

import React, { PureComponent } from "react";

class Demo extends PureComponent {
  state = {
    buttonList: [
      {
        key: "button1",
        enabled: false
      },
      {
        key: "button2",
        enabled: false
      }
    ]
  };

  onClick1 = (callerKey) => {
    const newButtonList = [...this.state.buttonList];

    const found = newButtonList.find((item) => item.key === callerKey);
    found.enabled = !found.enabled;

    this.setState({ buttonList: newButtonList });
  };

  onClick2 = (callerKey) => {
    this.setState((prevstate) => {
      const newButtonList = [...prevstate.buttonList];

      const found = newButtonList.find((item) => item.key === callerKey);
      found.enabled = !found.enabled;

      return {
        buttonList: newButtonList
      };
    });
  };

  render() {
    return (
      <div>
        <div
          onClick={() => this.onClick1("button1")}
          style={{ cursor: "pointer", marginBottom: "100px" }}
        >
          {`Button1 click on me (${this.state.buttonList[0].enabled})`}
        </div>
        <div
          onClick={() => this.onClick2("button2")}
          style={{ cursor: "pointer" }}
        >
          {`Button2 click on me (${this.state.buttonList[1].enabled})`}
        </div>
        ;
      </div>
    );
  }
}

export default Demo;

标签: javascriptreactjs

解决方案


推荐阅读