【发布时间】:2022-07-22 01:34:15
【问题描述】:
我是 React 新手,目前正在学习 useReducer。 我创建了一个简单的登录功能,用于验证用户输入的电子邮件是否包含“@”并且密码长度是否大于 5。 如果满足这两个条件,我希望我的程序在按下提交按钮时显示成功或失败消息的警报。
我很好奇的是,当我在 useEffect 中添加 dispatch({type: 'isCredValid')} 时,应用程序在提交时显示“成功”(在下面的代码中注释掉),但当我添加 dispatch({type: 'isCredValid'}) 时应用程序显示“失败”在 onSubmit 处理程序中不使用 useEffect。在没有 useEffect 帮助的情况下,在 onSubmit 处理程序中添加 dispatch({type: 'isCredValid')} 时,我希望应用程序显示“成功”。为什么不显示“成功”?以及为什么我的应用在派发函数在useEffect中时会显示“Success”?
减速机功能:
const credReducer = (state, action) => {
switch(action.type) {
case 'email' :
return {...state, email: action.value, isEmailValid: action.value.includes('@')};
case 'password' :
return {...state, password: action.value, isPasswordValid: action.value.length > 5 ? true : false};
case 'isCredValid' :
return {...state, isCredValid: state.isEmailValid && state.isPasswordValid ? true : false};
default :
return state;
}
}
组件和输入处理程序
const Login = () => {
const [credentials, dispatch] = useReducer(credReducer, {
email: '',
password: '',
isEmailValid: false,
isPasswordValid: false,
isCredValid: false
})
// useEffect(() => {
// dispatch({type: 'isCredValid'})
// }, [credentials.isEmailValid, credentials.isPasswordValid])
const handleSubmit = (e) => {
e.preventDefault()
dispatch({ type: "isCredValid" })
if (credentials.isCredValid === true) {
alert ("Success!")
} else {
alert ('failed')
}
}
const handleEmail = (e) => {
dispatch({ type: "email", value: e.target.value })
}
const handlePassword = (e) => {
dispatch({ type: "password", value: e.target.value })
}
return (
<Card className={classes.card}>
<h1> Login </h1>
<form onSubmit={handleSubmit}>
<label>Email</label>
<input type="text" value={credentials.email} onChange={handleEmail}/>
<label>Password</label>
<input type="text" value={credentials.password} onChange={handlePassword}/>
<button type="submit"> Submit </button>
</form>
</Card>
)
}
【问题讨论】:
-
dispatch 是一个异步函数,不会完成,您也不会在函数句柄提交中看到状态正在更新。如果你想捕捉它何时成功,你可以使用一个 useEffect 来监视状态变化
标签: reactjs react-hooks use-effect use-reducer