简体   繁体   English

在反应中获取数据第一次返回“未定义”

[英]Fetching data in react returns "undefined" at first time

I have a function component that I control user login with react.我有一个 function 组件,我通过反应控制用户登录。 According to the username and password entered in the input, if the value returned from the API is true, it redirects to another page, if false, it stays on the same page.根据输入的用户名和密码,如果API返回的值为true,则重定向到另一个页面,如果为false,则停留在同一页面。 When I press the button when the username and password are correct, the first value is It returns undifined, but when I press the button for the second time, it returns true and redirects to another page.当我在用户名和密码正确的情况下按下按钮时,第一个值为它返回未定义,但是当我第二次按下按钮时,它返回true并重定向到另一个页面。

console.log(isUser);控制台.log(isUser); // When I check, it shows undefined even though the values for the first name and password are full, but when I press the button again, it returns true if the username and password are correct. // 当我检查时,即使名字和密码的值已满,它也会显示未定义,但是当我再次按下按钮时,如果用户名和密码正确,则返回 true。

What is the reason of this?这是什么原因?

 export default function Login() {
      const [isUser, setUser] = useState();
      const [name, setName] = useState('');
      const [password, setPassword] = useState('');
      const [error, setError] = useState('');
    
      const history = useHistory();
      let control;
    
      function userControl() {
        debugger;
        let userService = new UserService();
        userService.getUserControl(name, password).then((result) => setUser(result.data.data));
        console.log(isUser);
    
        if (isUser == true) {
          history.push('/oee');
        } else {
          setUser(false);
          setError('Kullanıcı Adınız veya Şifreniz Hatalı');
          control = errorMessage();
        }
      }
    
      function errorMessage() {
        return (
          <div>
            <Message negative>
              <Message.Header>{error}</Message.Header>
            </Message>
          </div>
        );
      }
    
      return (
        <div>
          {control}
          <Grid textAlign="center" style={{ height: '70vh' }} verticalAlign="middle">
            <Grid.Column style={{ maxWidth: 450 }}>
              <Header as="h2" color="teal" textAlign="center">
                <Image style={{ height: 100, width: 200 }} src={ydclogo} />
              </Header>
              <Form size="large">
                <Segment stacked>
                  <Form.Input
                    fluid
                    icon="user"
                    iconPosition="left"
                    placeholder="User Name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                  />
                  <Form.Input
                    fluid
                    icon="lock"
                    iconPosition="left"
                    placeholder="Password"
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <Button color="teal" fluid size="large" onClick={userControl}>
                    Login
                  </Button>
                </Segment>
              </Form>
              <Message>L3 RAPORLAMA SİSTEMİ</Message>
            </Grid.Column>
          </Grid>
        </div>
      );
    }

userService.getUserControl is async operation. userService.getUserControl是异步操作。 To be able to use this response you should wrap your code in then() callback.为了能够使用此响应,您应该将代码包装在then()回调中。 But setting the state value using useState is also async operation and there is no guarantee that you will be able to read the actual value right after calling setUser .但是使用useState设置 state 值也是异步操作,并且不能保证在调用setUser后您将能够立即读取实际值。 You could do something like that:你可以这样做:

userService.getUserControl(name, password).then((result) => {
        const user = result.data.data
        setUser(user)

        if (user == true) {
          history.push('/oee');
        } else {
          setUser(false);
          setError('Kullanıcı Adınız veya Şifreniz Hatalı');
          control = errorMessage();
        }
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM