为什么状态没有更新?反应本机

时间:2020-04-02 00:10:50

标签: reactjs react-native react-native-android

我试图做一个简单的表格验证。如果按下按钮时字段用户名和密码不为空,则屏幕上将显示一条消息。但是,只有当我两次按下按钮时,消息才会出现,而当两个字段都不为空时,为什么?

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>
  );
}

// ...

1 个答案:

答案 0 :(得分:0)

与组件不同,状态更改后函数调用不会重新呈现,因此状态中的usernameError值与更改前的值相同。

尝试一下

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('');
    }
  }