【发布时间】:2019-12-06 05:35:42
【问题描述】:
我是原生反应新手。
我创建了一个 react native 应用程序,我的第一个屏幕是登录屏幕。我正在使用 onChangeText 使用用户名和密码更新状态变量,这最初效果很好。
但是,当我弹回登录屏幕时,“注销”。输入仍然包含我的用户名和密码。但是状态变量现在恢复为空。
我已尝试将输入值设置为 {this.state.username},但这只会在 2 次输入按下后导致状态深度错误,因此不起作用。
我错过了什么吗?
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, Alert, AsyncStorage, Linking } from 'react-native';
import { Input, Left, Spinner, Container, Item, Form, Header, Content, Label, Button } from 'native-base'
export default class Login extends Component {
state = { username: "", password: "", isLoaded: true }
static navigationOptions = {
header: null
}
constructor(props) {
super()
this.state.isLoaded = false
AsyncStorage.getItem("loggedIn").then(res => {
if (res === "true") {
this.props.navigation.navigate('List')
}
else {
this.setState({isLoaded: true})
}
})
}
checkLogin() {
if ((!this.state.username) || (!this.state.password)) {
Alert.alert('Error', 'Username/Password combination unknown', [{
text: 'Okay'
}])
return
}
....... snip ......
if (response === false) {
Alert.alert('Error', 'Username/Password combination unknown', [{
text: 'Okay'
}])
}
else {
AsyncStorage.setItem('user', JSON.stringify(response));
AsyncStorage.setItem('loggedIn', "true");
this.setState({username: null, password: null})
this.props.navigation.navigate('List')
}
}
}
render()
{
if (this.state.isLoaded == false) {
return (
<Container>
<Spinner />
</Container>
)
}
return (
<Container>
<Content>
<Image source={require('../../assets/logo.jpg')}/>
<Form>
<Item floatingLabel>
<Label>Username</Label>
<Input
autoCapitalize='none'
clearButtonMode='always'
onChangeText={text => this.setState({username:text})} />
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
clearButtonMode='always'
onChangeText={text => this.setState({password: text})} />
</Item>
<Button primary onPress={_ => this.checkLogin()}>
<Text style={styles.loginButtonText}>Login</Text>
</Button>
</Form>
</Content>
</Container>
);
}
}
【问题讨论】:
-
向我们展示您的代码!!
-
@DevAS 代码已添加,我在字段中没有 value={this.state.username},因为这会导致前面提到的深度问题
-
@Kevin 您需要找出深度问题 - 您确实想传递
value属性,以便组件作为受控组件工作。您能否提供有关深度问题的更多信息? -
这是返回的错误:
Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. -
我不确定这是否相关,但您的构造函数中的
super调用未通过props传递,如果与此无关将导致其他问题。应该是super(props);