【问题标题】:In React, why we need to render twice while we can do it render just once在 React 中,为什么我们需要渲染两次而我们​​可以只渲染一次
【发布时间】:2021-12-06 17:49:35
【问题描述】:

在 react docs 的文章 (https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html) 中,有以下内容:

Refs 在某些情况下(例如这种情况)很有用,但通常我们建议您谨慎使用它们。即使在演示中,这种命令式方法也不理想,因为会发生两次渲染而不是一次。

这是来自https://codesandbox.io/s/l70krvpykl?file=/index.js的演示的相关部分:

 handleChange = index => {
      this.setState({ selectedIndex: index }, () => {
      const selectedAccount = this.props.accounts[index];
      this.inputRef.current.resetEmailForNewUser(selectedAccount.email);
    });
  };

我调整了这个演示,我想出了一种方法来重新渲染一次(我删除了回调函数,因为它在 componentDidUpdate 之后运行,所以它会导致重新渲染两次):

 handleChange = index => {
      this.setState({ selectedIndex: index }); // set state of Parent Component (itself)
      const selectedAccount = this.props.accounts[index];
      this.inputRef.current.resetEmailForNewUser(selectedAccount.email); // set State of Child Component
  };

我想知道为什么这有效并且只重新渲染一次。我想可能会同时对 setState 做出反应。

我不知道为什么不建议这样做?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    使用 setState 回调“保证”只有在 {} 中的状态变量更新后才会执行此回调:

         this.setState({.... }, () => {to do only after state variables are updated})
    

    在您提到的第二种情况下,不能保证这种“顺序”执行会得到尊重。在这种情况下,您对受索引参数影响的对象的并行性没有任何问题。但是,如果有其他组件依赖于“selectedIndex”状态变量,您可能会遇到陌生问题,这在很大程度上取决于您如何构建它们。

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2023-01-24
      • 2021-07-27
      相关资源
      最近更新 更多