【问题标题】:nextProps and NextState are always equivalentnextProps 和 NextState 总是等价的
【发布时间】:2019-03-21 16:55:41
【问题描述】:

我了解在 shouldComponentUpdate 中使用 nextProps 和 nextState 来根据 this.state.someProperty 与 nextState.someProperty 的比较结果来确定组件是否应该重新渲染。如果它们不同,则组件应重新渲染。

这很清楚。

但是,这似乎不是正在发生的事情。查看此代码。

    class Box extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }

   this.counter = 
     this.counter.bind(this)
  }

  counter() {
    setInterval(()=>{
      this.setState({count: this.state.count+=1})
    }, 10000);
  }

  componentDidMount() {
    this.counter();
  }

  shouldComponentUpdate(nextProps, nextState) { 
    console.log(this.state.count + " " +  nextState.count)
    return true;
  }

  render() {
    return (
      <div> 
        <h1>This App Counts by the Second </h1>
        <h1>{this.state.count}</h1> 
    </div>
    );
  }
};

在 shouldComponentUpdate 中,我记录了 state.count 和 nextState.count 值,它们每次都是等价的。他们不应该不同吗?如果不是,如果使用 setState 更改状态确保它们相同,那么检查它们是否等效的目的是什么?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    nextState 和 currentState 总是相同的,因为您在更新原始状态对象时对其进行了变异

      counter() {
        setInterval(()=>{
          this.setState({count: this.state.count+=1})  // mutation done here
        }, 10000);
      }
    

    为了解决这个问题,你必须使用函数式 setState 之类的

    counter() {
        setInterval(()=>{
          this.setState(prevState => ({count: prevState.count + 1}))
        }, 10000);
      }
    

    【讨论】:

    • 谢谢!在您的示例中, prevState 变量在哪里定义?它从何而来?这是从 setState 传递的东西吗?
    • this.state.count+1 不也可以吗?只需从语句中删除变异的 +=
    • @SamiKuhmonen,是的,它会起作用,但建议在根据前一个更新当前状态时使用功能 setState 以避免任何不一致。这就是我提出上述答案的原因
    • @SamiKuhmonen 您可以阅读此答案以获取更多详细信息stackoverflow.com/questions/48209452/…
    • @WriterState,请查看我上面评论中的链接以了解更多关于它是如何工作的,并查看 setState 的文档
    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多