首页 > 解决方案 > 为什么反应组件类的实例变量(不是状态变量)没有在构造函数中初始化值?

问题描述

我对 React Component 类变量(不是状态变量)有一个奇怪的问题。我在 Component 类中定义了一些变量。我在 shouldComponentUpdate() 函数中使用这个变量来决定组件是否应该更新。为简单起见,让我们说:

constructor(props) {
super(props);
this.variable = false;
console.log(this.variable);
}
shouldComponentUpdate(nextProps, nextState) {
   console.log(this.variable);
   if(this.variable === false) {
      this.variable = true;
      return true;
   }
   return false;
}

问题是:当我刷新我的网页时,constructor首先被调用,然后我的shouldComponentUpdate()函数被调用,但这里this.variable碰巧是true。为什么会发生这种情况?谁做this.variabletrue

PS:我正在使用开发环境:http://localhost:3000,如果它与此有任何关系。

标签: reactjs

解决方案


推荐阅读