【问题标题】:React.js understanding setState()React.js 理解 setState()
【发布时间】:2021-07-25 00:51:21
【问题描述】:

我正在学习 React.js 并阅读 react.js 官方文档。官方文档提供了一个示例,我对此有疑问:

原代码:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

我的问题是: 在handleClick方法中,为什么this.setState不能写成(没有箭头函数):

handleClick() {
    this.setState({
      isToggleOn: !prevState.isToggleOn
    });
}

【问题讨论】:

  • 你可以,只要你使用isToggleOn: !this.state.isToggleOn (因为现在你在你的例子中凭空提取prevState,而在页面的示例代码中, setState 被调用可调用函数,该变量是函数的参数,由 React 自动填充)

标签: javascript reactjs


【解决方案1】:

您不能这样做的原因是 prevState 将是 undefined 并且您无法访问 undefined 对象上的属性键。每当您想根据之前的状态更改逻辑时,您都应该使用回调函数,这样您就可以避免不必要的直接状态突变。

【讨论】:

    【解决方案2】:

    在这种情况下,两者都可以。但有时在更改前一个状态值的状态时会得到意外的输出。欲了解更多信息,请访问 React's setState method with prevState argument

    你可以在那里理解。

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多