当前位置 : 主页 > 网页制作 > React >

reactjs – 使用React Hook重置为初始状态

来源:互联网 收集:自由互联 发布时间:2021-06-15
我目前正在处理一个注册表单,以下是我的代码片段: const Signup = () = { const [username, setUsername] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [passwordCon
我目前正在处理一个注册表单,以下是我的代码片段:

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

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

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

非常必须手动将每个状态设置回空字符串inclearState我想知道是否有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="http://img.558idc.com/uploadfile/allimg/210615/1P21W0O-0.jpg"></script>
<script src="http://img.558idc.com/uploadfile/allimg/210615/1P21U2D-1.jpg"></script>

<div id="root"></div>
网友评论