【问题标题】:React hooks form doesn't reset the text fields even after submitting the data即使在提交数据后,React hooks 表单也不会重置文本字段
【发布时间】:2021-08-11 23:10:57
【问题描述】:

即使在将数据提交到服务器后,React hooks 表单也不会重置文本字段。我已经打电话给setRegister({...initialState});,但它不关心也不重置字段,有人可以告诉我可能是什么原因吗?

const [formRegister, setRegister] = useState({ _id: "", nomineename: "", email: "", description: "", nominatedby: ""});

const onChange = (e) => {
    e.persist();
    setRegister({ ...formRegister, [e.target.name]: e.target.value });
}
const initialState = {
    _id:"",
    nomineename: "",
    email: "",
    description: "",
    nominatedby: ""
};
const onSubmit = () => {
        const fetchData = async () => {
            try {
                const res = await Axios.post('http://localhost:8000/service/nominateperson', formRegister);
                if (res.data) {
                    console.log("Link token created:" + res.data);
                    const successMessage = res.data.message;
                    setHelperText(successMessage);
                    setRegister({...initialState});
                }
            } catch (e) {
                console.log(e);
                history.push('/errorPage');
            }
        }
        fetchData();
    }

return (
        <div className="App">
            <h1>Nominate Person</h1>
            <form onSubmit={handleSubmit(onSubmit)}  className="linkForm inputForm" >
                <div className="inputField" >
                    <input name="nomineename" 
                    placeholder="nominate a person" 
                    type="text" 
                    {...register('nomineename',{
                        required: "Nominate a person is required !",
                        pattern: {
                          value: /^[a-zA-Z\s]/,
                          message: "Invalid name !"
                        }
                      })
                    }
                      onChange={onChange}
                    /> 
                </div>
                <span className="nominateError"><pre>{errors.nomineename && errors.nomineename.message}</pre></span>
                <div className="inputField" >
                    <input name="email" 
                    placeholder="nominee email" 
                    type="text" 
                    {...register('email',{
                        required: "Nominee email is required !",
                        pattern: {
                            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                           message: "Invalid email address !"
                        }
                      })}
                      onChange={onChange}
                    />
                </div>
                <span className="nominateError"><pre>{errors.email && errors.email.message}</pre></span>
                <div className="inputField" >
                    <textarea name="description" 
                    placeholder="reason for nomination"
                    {...register('description',{
                        required: "Description is required !",
                        pattern: {
                            value: /^[a-zA-Z,.!""\s]{10,1000}$/,
                            message: "Min of 10 or not more than 1000 characters !"
                        }
                      })}
                      onChange={onChange}
                    />
                </div>
                <span className="nominateError"><pre>{errors.description && errors.description.message }</pre></span>
                <div className="inputField nominatedby" >
                    <input name="nominatedby" 
                    placeholder="nominated by" 
                    type="text" 
                    {...register('nominatedby',{
                        required: "Nominated by is required !",
                        pattern: {
                          value: /^[a-zA-Z\s]{2,30}$/,
                          message: "Invalid name !"
                        }
                      })}
                      onChange={onChange}
                    /> 
                </div>
                <span className="nominateError"><pre>{errors.nominatedby && errors.nominatedby.message}</pre></span>
                <span className="getlinkbutton">
                    <input type="submit"/>
                </span><br></br><br></br>
                <label>
                    <span className="loginValidationText">{helperText}</span>
                </label>
            </form>
        </div>
    )

https://codesandbox.io/s/xenodochial-tereshkova-51t97?file=/src/App.js

【问题讨论】:

  • 看起来你没有显示整个图片,看起来你试图从use-react-form lib重置一个表单,这不是它的完成方式。请做一个完整的例子How to create a Minimal, Reproducible Example
  • 我添加了一个最小的codeandbox链接供参考
  • 除了我的回答之外,当您已经使用表单库时,使用另一个状态formRegister 没有意义,您已经在提交事件和钩子状态中拥有它的状态。检查文档示例。

标签: reactjs react-hooks


【解决方案1】:

表单状态由useForm 控制,不是由您的formRegister 状态控制。

因此,要重置表单字段/状态,您需要使用其reset API

const { reset } = useForm();

const onSubmit = () => {
  reset(initialState);
  const fetchData = async () => {
    try {
      ...
      if (res.data) {
        ...
        reset(initialState);
        setRegister({ ...initialState });
      }
    } catch (e) {
      ...
    }
  };
  fetchData();
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 2021-02-03
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多