当我使用正确的电子邮件和密码时,它可以正常工作。
但是,如果电子邮件和密码不正确,则会出现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>
)
答案 0 :(得分:0)
通常,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()
}
我希望您不要在前端依赖此代码。因为验证登录名和信息完全绝对不安全 这样的密码=)