javascript - 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
显示aFlag
为false
引用的console.log 是this.aFlag
什么?
我有范围问题吗?
解决方案
在这里查看生命周期图。它似乎renderItem
在之前执行componentDidMount()
推荐阅读
- sql-server - 从 SQL Server 迁移到 POSTGRESQL 时的日期函数问题
- react-native - React Native React-Hook-Form 重置
- reactjs - Electron/React:如何避免使用递归文件/文件夹枚举阻塞主线程
- macos - Mac应用程序安装在开发人员机器上的未知位置
- javascript - 如何解决冲突的Javascript?
- python - Playwright:获取所选元素的完整 XPATH
- python - 无法找到 HTML 元素源
- android - IllegalStateException: Activity 没有设置 NavController
- c++ - /usr/include/c++/8/cstdlib:75:15:致命错误:stdlib.h:没有这样的文件或目录
- javascript - 在 POST 方法中传递值