[英]Why the state didn't update? React Native
I tried to do a simple form validation.我试图做一个简单的表单验证。 If the field username and password aren't empty when the button is pressed, a message is shown in the screen.
如果按下按钮时用户名和密码字段不为空,屏幕上会显示一条消息。 But the message appear only when I press the button twice, ever when the two fields aren't empty, why?
但是只有当我按下按钮两次时才会出现消息,当两个字段不为空时,为什么?
export default function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [usernameError, setUsernameError] = useState(false);
const [passwordError, setPasswordError] = useState(false);
const [loginMessage, setLoginMessage] = useState('');
async function handleLogin() {
if (username === '') {
setUsernameError('Username field is empty');
} else {
setUsernameError('');
}
if (password === '') {
setPasswordError('Password field is empty');
} else {
setPasswordError('');
}
if (usernameError === '' && passwordError === '') {
setLoginMessage(`Hello ${username} you have successfully logged in!`);
} else {
setLoginMessage('');
}
}
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<Text style={styles.header}>Login Panel</Text>
<Text>{loginMessage}</Text>
<TextInput
style={usernameError ? styles.validationError : styles.textInput}
placeholder='username'
onChangeText={text => setUsername(text)}
/>
<Text style={{ color: 'red' }}>{usernameError}</Text>
<TextInput
style={passwordError ? styles.validationError : styles.textInput}
placeholder='password'
secureTextEntry
onChangeText={text => setPassword(text)}
/>
<Text style={{ color: 'red' }}>{passwordError}</Text>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.Button} onPress={handleLogin}>
<Text style={styles.ButtonText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Button}>
<Text style={styles.ButtonText}>Logout</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
// ...
Unlike components, function calls didn't re-render after state change, so the value of usernameError
from your state is the same as before you changed it.与组件不同,函数调用在状态更改后不会重新渲染,因此状态中
usernameError
的值与更改之前相同。
Try this尝试这个
async function handleLogin() {
var errorUsername = ''
var errorPassword = ''
if (username === '') {
setUsernameError('Username field is empty');
errorUsername = 'Username field is empty'
} else {
setUsernameError('');
}
if (password === '') {
setPasswordError('Password field is empty');
errorPassword = 'Password field is empty'
} else {
setPasswordError('');
}
if (errorUsername === '' && errorPassword === '') {
setLoginMessage(`Hello ${username} you have successfully logged in!`);
} else {
setLoginMessage('');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.