登录验证警报消息未在ui中呈现

因此,我使用api中接收的电话号码作为参数进行身份验证,以从特定用户中检索数据。现在,我只想处理api收到api中没有的数字时的情况。为此,即时消息使用实质性ui警报显示给用户,但是当我输入错误的数字时,即时消息仍然收到错误(无法读取未定义的'user'属性),并且未在UI中发出警报。这是代码:

 const Login = () => {
    const history = useHistory()
    const location = useLocation()
    const [state, setState] = useState('')
    const [data, setData] = useState({});
    const phone = state
    ...
    let headers = new Headers();
    headers.set("Authorization", "Basic " + btoa(username + ":" + password));

    const handleClick = () => {
    getData();
    };

    const getData = async () => {
    const a = await fetch(url, { method: "GET", headers: headers });
    const response = await a.json();
    const respData = response.user[0].attributes[0]
    setData(respData);
    history.push(`/user/${respData.name}`)
    };

    const onTextChange = event => {
    setState(event.target.value);
    }
return (
<div>
    <input onChange={onTextChange}>
    <Button onClick={handleClick} >
      login
    </Button>
 {(data.user || []).map((data) => 
            (data.length == 0)? (
              <Alert severity="error" className={styles.alert}>
                Incorrect phone number . Try again!
              </Alert>
            ) : (
              <></>
            )
            ) }
</div>
)
评论
  • 中央一套
    中央一套 回复

    上面的问题有几个错误。由于第一个错误,它不应该编译。

    • input tag is not closed. <input />
    • data is an object and not array. you are checking length of data object. And even if it's an array with length 0 then you need if-else expression rather then map. Map will not be called in your case.
    {!!data.user.length && (
    <Alert severity="error" className={styles.alert}>
    An alert message to user!
    </Alert>
    )}
    

    在这种情况下,不需要最后一个<>

  • 头碰头
    头碰头 回复

    You should add try/catch block arround the place you await your request and do your error handling there (that is, not use response.user[0].attributes[0] upon HTTP error response and avoid Cannot read property 'user' of undefined runtime error).

    try {
       const a = await fetch(url, { method: "GET", headers: headers });
       const response = await a.json();
       const respData = response.user[0].attributes[0]
       setData(respData);
       history.push(`/user/${respData.name}`)
    }
    catch (err) {
      // error handling
    }
    

    我建议在状态中使用一个布尔标志,或者如果决定更复杂,则使用一个函数来指示是否显示警报。它将大大简化视图中的逻辑。