javascript - 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>
)
解决方案
通常,方法的逻辑条件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()
}
我希望你不要依赖前端的这段代码。因为以这种方式验证登录名和密码是绝对不安全的 =)
推荐阅读
- php - Laravel throws InvalidArgumentException View [.profilePage.{user}] not found
- c - 美元如何?与 c 退出代码一起使用?
- angular6 - 从Angular 6中的父组件访问子组件的ChangeDetectorRef或ComponentRef,而不将其注入子组件
- arrays - 如何从另一个类 VB.NET 将项目添加到数组
- c++ - 如何随机化双精度/浮点数据类型?C++
- javascript - HERE 地图 - 将标记从一个位置移动到另一个位置
- python - 如何在for循环python中获取一堆值的平均值、最小值等
- reactjs - 如何加入两个 React Native 应用程序
- r - 将 mapply 生成的列表转换为矩阵或数据框
- python - Kivy:自定义类与 ScreenManager 不兼容(?)