React Native报错:Cannot read property 'email' of undefined 求助
解决React Native中"Cannot read property 'email' of undefined"的问题
嘿,这个问题我之前也踩过坑!核心原因是**getUser方法里的this没有指向你的组件实例**,导致this.state变成了undefined,自然就找不到email属性了。下面给你三种简单的解决办法,任选其一就行:
方法1:在构造函数中绑定this
在组件的constructor里,给getUser方法绑定组件的this上下文,这样不管怎么调用它,this都会牢牢指向组件实例:
constructor(){ super() this.state = { email: '', password: '', } // 新增这行代码,绑定this this.getUser = this.getUser.bind(this); }
方法2:在onPress中用箭头函数包裹回调
把onPress的回调改成箭头函数形式,箭头函数会自动继承当前上下文的this,调用getUser时this就会是组件实例了:
<Button title="Login" accessibilityLabel="Login" onPress={() => this.getUser()} // 用箭头函数包裹getUser调用 />
方法3:把getUser定义成箭头函数
直接用箭头函数来声明getUser方法,它的this会自动绑定到组件实例,不需要额外做绑定操作:
// 把原来的函数定义改成箭头函数 getUser = () => { console.log(this.state.email); console.log(this.state.password); }
这三种方法都能完美解决你的问题,选你觉得最顺手的就行~我个人平时更常用方法1或者方法3,稳定性都很不错。
内容的提问来源于stack exchange,提问作者jrocc
相关产品推荐
相关产品推荐

