首页 > 解决方案 > React Native 类变量显示两个不同的值...解释是什么?

问题描述

这是我的示例代码......大多数东西都被剥离了......

class MyView extends Component {

aFlag = true //initialize class variable here

componentDidMount() {
 // for some reason even after this component unmounts and mounts again this class variable stays at false (a value that we set in this compoment at some point)...
 this.aFlag = true // (1) ***** IF I TAKE THIS OUT...the console log for this.aFlag below is FALSE
 console.log('this', this) // (2) shows a MyView Object, aFlag key has value FALSE!!!
 console.log('this.aFlag:', this.aFlag)// (3) this console log show TRUE

//other code here that uses this.aFlag removed...

}
...

renderItem = () => {
//other code removed...
if (some condition) this.aFlag = false
}

render(){
<Flatlist
renderItem={this.renderItem}
...other code removed
/>
}

我有一个简单的类,其类变量在类定义中初始化为 true。

这就是发生的事情。实例化组件...componentDidMount 记录我上面在评论中显示的内容。这是为什么?

为什么控制台日志this显示aFlagfalse

引用的console.log 是this.aFlag什么?

我有范围问题吗?

标签: javascriptreactjsreact-native

解决方案


在这里查看生命周期图。它似乎renderItem在之前执行componentDidMount()


推荐阅读