遗憾的是,没有内置的方法可以将状态设置为其初始值。
您的代码看起来不错,但是如果您想减少所需的功能,则可以将整个表单状态放在单个状态变量对象中,然后重置为初始对象。
例
const { useState } = React;function signupUser() { return new Promise(resolve => { setTimeout(resolve, 1000); });}const initialState = { username: "", email: "", password: "", password/confirm/iation: ""};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={password/confirm/iation} name="password/confirm/iation" 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>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)