首页 > 解决方案 > TypeError:无法读取未定义的属性“电子邮件”

问题描述

当我使用正确的电子邮件和密码时,它工作正常。

但是当电子邮件和密码不正确时,我得到:Can't read property 'email' of undefined错误。我想在该if/else部分处理它。

请帮忙。谢谢

const {customers} = useContext(customersContext)
    const [customerEmail, setCustomerEmail] = useState("")

    const [password, setPassword] = useState("")

    const history = useHistory();

    const currentUser = customers.find((s, index)=> s.email === customerEmail)

    const handleLogin = (e) => {
        e.preventDefault()
        if(currentUser.email === customerEmail && currentUser.password === password)
        {
            localStorage.setItem("customers", currentUser.id) 
            history.push("/home") 
            props.togle()  
        }
        else if(typeof currentUser.email === undefined)
        {
            window.alert("email does not match")
        }
        else {
            window.alert("No match found")
        }
    }
   
    return (
        <div>
            <Form>
                <FormGroup>
                    <Label for="email">customerEmail</Label>
                    <Input type="email" name="email" onChange={(e) => setCustomerEmail(e.target.value)}/>
                </FormGroup>
                <FormGroup>
                    <Label for="password">Password</Label>
                    <Input type="password" name="password" onChange={(e) => setPassword(e.target.value)} />
                </FormGroup>
                <Button onClick={handleLogin}> Submit </Button>
            </Form>
        </div>
    )

标签: javascriptreactjs

解决方案


通常,方法的逻辑条件handleLogin可能如下所示:

if (currentUser === undefined) {
  window.alert("No match found")
// You shouldn't give a user a tip of what part in the login/password combination doesn't match, because it will make the brute forcing attempts way much easier
} else if (currentUser.email !== customerEmail || currentUser.password !== password) {
  window.alert("email or password does not match")
} else {
  localStorage.setItem("customers", currentUser.id) 
  history.push("/home") 
  props.togle()  
}

我希望你不要依赖前端的这段代码。因为以这种方式验证登录名和密码是绝对不安全的 =)


推荐阅读