gpt4 book ai didi

reactjs - 使用 React Hooks 重置为初始状态

转载 作者:行者123 更新时间:2023-12-03 12:57:31 24 4
gpt4 key购买 nike

我目前正在制作注册表单,以下是我的代码片段:

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是否有一个方法或函数可以将状态重置回其初始值?

最佳答案

遗憾的是,没有内置方法可以将状态设置为其初始值。

您的代码看起来不错,但如果您想减少所需的功能,您可以将整个表单状态放入单个状态变量对象中并重置为初始对象。

示例

const { useState } = React;

function signupUser() {
return new Promise(resolve => {
setTimeout(resolve, 1000);
});
}

const initialState = {
username: "",
email: "",
password: "",
passwordConfirmation: ""
};

const Signup = () => {
const [
{ username, email, password, passwordConfirmation },
setState
] = useState(initialState);

const clearState = () => {
setState({ ...initialState });
};

const onChange = e => {
const { name, value } = e.target;
setState(prevState => ({ ...prevState, [name]: value }));
};

const handleSubmit = e => {
e.preventDefault();
signupUser().then(clearState);
};

return (
<form onSubmit={handleSubmit}>
<div>
<label>
Username:
<input value={username} name="username" onChange={onChange} />
</label>
</div>
<div>
<label>
Email:
<input value={email} name="email" onChange={onChange} />
</label>
</div>
<div>
<label>
Password:
<input
value={password}
name="password"
type="password"
onChange={onChange}
/>
</label>
</div>
<div>
<label>
Confirm Password:
<input
value={passwordConfirmation}
name="passwordConfirmation"
type="password"
onChange={onChange}
/>
</label>
</div>
<button>Submit</button>
</form>
);
};

ReactDOM.render(<Signup />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

关于reactjs - 使用 React Hooks 重置为初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54895883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com