【问题标题】:Fetching data in react returns "undefined" at first time在反应中获取数据第一次返回“未定义”
【发布时间】:2021-12-27 11:23:54
【问题描述】:

我有一个功能组件,我用反应控制用户登录。根据输入的用户名和密码,如果API返回的值为true,则重定向到另一个页面,如果为false,则停留在同一页面上。当我在用户名和密码正确的情况下按下按钮时,第一个值为它返回 undifined ,但当我第二次按下按钮时,它返回 true 并重定向到另一个页面。

console.log(isUser); // 当我检查时,即使名字和密码的值已满,它也显示未定义,但是当我再次按下按钮时,如果用户名和密码正确,则返回true。

这是什么原因?

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    userService.getUserControl 是异步操作。为了能够使用此响应,您应该将代码包装在 then() 回调中。但是使用useState 设置状态值也是异步操作,不能保证在调用setUser 之后就可以读取实际值。你可以这样做:

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

    【讨论】:

    • 我尝试了您的更改,但不幸的是它第一次返回未定义。那么有什么办法可以防止这种时间滑移呢?
    • 究竟返回了什么undefined?
    • 如果要立即使用响应,直接使用响应中的值,如result.data.data,不要使用isUser
    • 谢谢你,我觉得 useState 让我失望了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2018-02-21
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2023-04-07
    相关资源
    最近更新 更多