我目前正在处理一个注册表单,下面是我的代码片段:
const Signup = () => {
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [passwordConfirmation, setPasswordConfirmation] = useState('')
const clearState = () => {
setUsername('')
setEmail('')
setPassword('')
setPasswordConfirmation('')
}
const handleSubmit = signupUser => e => {
e.preventDefault()
signupUser().then(data => {
console.log(data)
clearState() // <-----------
})
}
return <JSX />
}
export default Signup
每个状态片段用于窗体的受控输入。
本质上,我想要做的是在用户成功注册之后,我希望状态返回到清除字段后的初始状态。
在 clearState
中手动将每个状态设置回空字符串是非常必要的,我想知道是否有一个方法或函数可以用 React 将状态重置回它的初始值?