为什么我收到错误"无法在反应本机中读取未被蔑视的属性'状态'?



我非常需要你的帮助。我试图在我的状态属性中创建一个JSON对象用户,以检查我的身份验证是如何工作的。但当我试图获得访问权限时,我收到了错误";无法读取未设防的"的属性"state";错误箭头指向代码的这一部分const{users,textInputEmail,textInputPassword}=this.state。此外,当我尝试检查用户时,它也显示"未定义"。我做错了什么?

import React, { Component } from 'react'
import { View, TextInput } from 'react-native'
import { MyButton, ErrorMessage } from '../uikit'
import { FormStyle, InputStyle } from '../constants/styles'
import { SIGN_IN, SUCCESS } from '../routes'
export class LogIn extends Component {
state = {
users: {
user: [
{
name: 'john1303@ukr.net',
password: '12345678'
},
{
name: 'steve13@gmail.com',
password: '87654321'
}
],
},
textInputEmail: '',
textInputPassword: ''
}
isUser() {
console.log(users)
const { users, textInputEmail, textInputPassword } = this.state
let currentUser, password;
currentUser = users.map((user) => user.name == textInputEmail ? user : 'unknown')
if (currentUser == 'unknown')
return alert('Incorrect user or password!')
else {
if (currentUser.password == textInputPassword)
this.props.navigation.navigate(SUCCESS)
}
}
render() {
const { mainContainer, buttons } = FormStyle
const { container, text } = InputStyle
return (
<View>
<View style={mainContainer}>
<View style={container}>
<TextInput
style={text}
placeholder={'Email/Login'}
onChangeText={(value) => this.setState({ textInputEmail: value })}
>
</TextInput>
<ErrorMessage errorText={'Incorrect email'} />
</View>
<View style={container}>
<TextInput
style={text}
placeholder={'Password'}
secureTextEntry={true}
onChangeText={(value) => this.setState({ textInputPassword: value })}
>
</TextInput>
<ErrorMessage errorText={'Incorrect password'} />
</View>
<View style={buttons}>
<MyButton
name={'Log in'.toUpperCase()}
onPress={this.isUser} />
<MyButton
name={'Sign in'.toUpperCase()}
onPress={() => this.props.navigation.navigate(SIGN_IN)} />
</View>
</View>
</View>
)
}
}

在React类组件中,您需要bind函数才能具有正确的this值。有几种方法可以做到这一点,请参阅此处。

您可以将isUser声明更改为:

isUser() {
...
}

收件人:

isUser = () => {
...
}

或者你可以通过添加一个构造函数来绑定它,比如:

export class LogIn extends Component {
constructor(props) {
super(props);
this.isUser = this.useUser.bind(this);
}
...
}

或者您可以直接在render中绑定函数,如下所示:

<MyButton
name={'Log in'.toUpperCase()}
onPress={this.isUser.bind(this)} />

执行此操作时:

onPress={this.isUser}

您正在从组件的作用域中分离isUser,当它自己被调用时;这个";未定义。您可以通过创建一个只调用this.isUser():的箭头函数来修复它

onPress={() => this.isUser()}

或者通过使isUser本身成为箭头函数:

isUser = () => {
...
}

如果你对它的不同之处以及为什么重要感兴趣,我已经在其他地方对此进行了更详细的解释。

相关内容

最新更新