栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用React Hooks重置为初始状态

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668837.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号