使用 React Hooks 重置为初始状态 [英] Reset to Initial State with React Hooks

查看:60
本文介绍了使用 React Hooks 重置为初始状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理一个注册表单,以下是我的代码片段:

const Signup = () =>{const [username, setUsername] = useState('')const [email, setEmail] = useState('')const [密码,setPassword] = useState('')const [passwordConfirmation, setPasswordConfirmation] = useState('')const clearState = () =>{设置用户名('')设置电子邮件('')设置密码('')setPasswordConfirmation('')}const handleSubmit = signupUser =>e =>{e.preventDefault()signupUser().then(data => {控制台日志(数据)clearState()//<-----------})}返回 }导出默认注册

每个状态用于表单的受控输入.

本质上我想做的是在用户成功注册后,我希望状态回到初始状态并清除字段.

clearState 中手动将每个状态重新设置为空字符串是非常必要的 我想知道是否有 React 附带的方法或函数可以将状态重置回其初始值?

解决方案

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

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

示例

const { useState } = React;函数注册用户(){返回新的承诺(解决 => {设置超时(解决,1000);});}常量初始状态 = {用户名: "",电子邮件: "",密码: "",确认密码: ""};const 注册 = () =>{常量 [{用户名,电子邮件,密码,密码确认},设置状态] = 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);};返回 (<form onSubmit={handleSubmit}><div><标签>用户名:<input value={username} name="username" onChange={onChange}/>

<div><标签>电子邮件:<input value={email} name="email" onChange={onChange}/>

<div><标签>密码:<输入值={密码}名称=密码"类型=密码"onChange={onChange}/>

<div><标签>确认密码:<输入值={密码确认}名称=密码确认"类型=密码"onChange={onChange}/>

<按钮>提交</表单>);};ReactDOM.render(, document.getElementById("root"));

<script src="https://unpkg.com/react@16/umd/react.development.js"><;/脚本><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="root"></div>

I'm currently working on a signup form and the following is a snippet of my code:

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

Each piece of state is used for a controlled input for the form.

Essentially what I want to do is after the user has successfully signed up, I want the state to go back to the initial state with the fields cleared.

It's quite imperative to manually set each piece of state back to empty strings inclearState I was wondering if there is a method or function that comes with React that resets the state back to its initial values?

解决方案

There is no built-in way to set the state to its initial value, sadly.

Your code looks good, but if you want to decrease the functions needed you can put your entire form state in a single state variable object and reset to the initial object.

Example

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>

这篇关于使用 React Hooks 重置为初始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆