为什么React Native中出现"Cannot read property 'state' of undefined"报错?
问题原因及修复方案
1. 核心报错Cannot read property 'state' of undefined的原因
这是类方法this指向丢失导致的:你直接将普通类方法isUser绑定给按钮的onPress事件时,方法运行时的this不会自动指向组件实例,最终访问this.state时this为undefined。
修复方式二选一即可:
- 将
isUser方法改为箭头函数,自动绑定组件实例的this - 绑定
onPress时改成onPress={() => this.isUser()},调用时绑定实例this
2. console.log(users)返回undefined的原因
这行打印代码写在const { users, textInputEmail, textInputPassword } = this.state解构赋值之前,此时当前作用域内还未声明users变量,自然返回undefined,把打印逻辑移到解构代码之后即可。
3. 后续逻辑隐藏错误
你定义的state里users是包含user数组的对象,不是数组本身,直接调用users.map()会抛出类型错误,需要访问users.user才能拿到存储用户的数组。另外用map遍历匹配用户的逻辑不符合需求:map会返回和原数组长度一致的新数组,你无法直接判断是否等于'unknown',改用Array.find()方法更适配匹配单个用户的场景。
修复后的isUser示例代码
// 改为箭头函数自动绑定this isUser = () => { const { users, textInputEmail, textInputPassword } = this.state // 从users下的user数组匹配用户 const currentUser = users.user.find(user => user.name === textInputEmail) if (!currentUser || currentUser.password !== textInputPassword) { return alert('Incorrect user or password!') } this.props.navigation.navigate(SUCCESS) }
内容的提问来源于stack exchange,提问作者Vladimir
相关产品推荐
相关产品推荐

