使用React Hooks重置为初始状态

使用React Hooks重置为初始状态,第1张

使用React Hooks重置为初始状态

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

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

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>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5674092.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存