根据渲染函数中的前一个设置状态

Яро*_*щук 5 javascript setstate reactjs

我最近阅读了 react.js文档,发现根据之前的状态值设置状态不一致。这是那块代码:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为这种() => this.setState({ count: this.state.count + 1 })设置方式state是错误的,您应该为此目的使用回调。所以我提出了PR,其中我添加了对先前状态的回调函数的使用,但它已被弃用,因为

当您不确定捕获的状态值是什么时,回调版本很有用。

我真的不喜欢当你不是解释的某个部分时,有人可以解释为什么这种() => this.setState({ count: this.state.count + 1 })设置状态的方式是正确的。

提前致谢。

got*_*to1 1

在当前的示例中,您将默认状态设置为{ count: 0 },这样做是“安全”的setState({ count: this.state.count + 1 }),因为当您第一次更新状态时,0 + 1将产生有效的结果。

class App extends React.Component {
  state = { count: 0 }
  render() {
    return (
      <div>
         <p>You clicked {this.state.count} times</p>
         <button
           onClick={() => this.setState({ count: this.state.count + 1 })}
         >
           Click me!
         </button>
      </div>
    )
  }
}
ReactDOM.render(
  <App />,
  document.getElementById("app")
)
Run Code Online (Sandbox Code Playgroud)
<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="app"></div>
Run Code Online (Sandbox Code Playgroud)

但是,我们假设您的某些部分的初始值state不是0,因此调用this.state.count + 1可能会产生无效结果。您可以在此处获取该callback版本,因为:

你不确定状态的捕获值是多少。

class App extends React.Component {
  state = { count: null }
  render() {
    const handleClick = () => {
      this.setState((prevState) => {
        // count is initially `null`, so 
        // `null + 1` could yield an undesired result
        if (!Number.isInteger(prevState.count)) {
          return { count: 1 }
        }
        return { count: prevState.count + 1 }
      })
    }
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={handleClick}>
          Click me!
        </button>
      </div>
    ) 
  }
}
ReactDOM.render(
  <App />,
  document.getElementById("app")
)
Run Code Online (Sandbox Code Playgroud)
<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="app"></div>
Run Code Online (Sandbox Code Playgroud)

这只是一个例子,但你已经明白了。


您的 PR 很可能被拒绝,因为文档中的示例是正确的,假设在通过执行 更新您的状态是“安全”的相同上下文中使用this.setState({ count: this.state.count + 1 })

这是文档:

这两种更新方式state都是正确的,应该在适当的时候使用。正如您在第二个示例中所看到的,如果想在更新state.

尽管如此,文档中的示例是正确的,如果使用“回调选项”,则不会产生任何好处。