我目前正在制作一份注册表格,以下是我的代码片段:

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

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

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

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

推荐答案

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

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

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>

Reactjs相关问答推荐

表格提交中的react 路由导航

如果Next JS中使用await,monaco-editor将继续加载

react-hook-form问题:为什么getValues不返回大多数当前值?

Inbox Enum类型以React组件状态时出现TypScript错误

在Redux工具包查询中,是否可以将标记应用到API切片内的所有端点?

无法将react 路由状态从路由传递给子组件

react -无法获取函数的最新参数值

状态更改是否卸载功能组件

获取类别和页面的参数

Spring Boot + React + MySQL应用的架构层面有哪些?

React - 函数组件 - 点击两次问题处理

无法设置 null 的属性(设置src)

使用状态与复选框不同步

作为单个变量的 React 组件是否比 memoized 组件渲染得更快?

DatePicker MUI 如何在日历左侧显示清除文本

将复杂状态和 setState 传递给更简单的 api

在 Spring Cloud Gateway 中运行的 React SPA 页面刷新出现白标错误

SonarCloud 代码覆盖率不适用于 Github Action

如何定制 React 热 toastr ?

试图将页面限制为仅登录但有条件的用户似乎永远不会运行