首页 > 解决方案 > 即使不成功,在 onSubmit 后重置状态值

问题描述

我有一个表单,如果我提交并返回错误,我会对其进行编程以显示错误在哪里。仅修复错误后,我提交失败,因为正在重置状态并且将空值发送到 api。我将在下面显示一些代码:

const AddProject = (props) => {
  const [values, setValues] = useState({
    projectName: '', projectIdentifier: '', description: '', startDate: '', endDate: '', errors: {},
  });

  useEffect(() => {
    if (props.errors) {
      setValues({ errors: props.errors });
    }
  }, [props.errors]);

  const onChange = (e) => {
    const { name, value } = e.target;
    console.log(values);
    setValues({ ...values, [name]: value });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const newProject = {
      projectName: values.projectName,
      projectIdentifier: values.projectIdentifier,
      description: values.description,
      startDate: values.startDate,
      endDate: values.endDate,
    };

    props.createProject(newProject);
  };

在下面创建项目操作

const createProject = (project) => async dispatch => {
  try {
    await axios.post('http://localhost:8080/api/project', project);
    window.history.back();
  } catch (e) {
    dispatch({
      type: GET_ERRORS,
      payload: e.response.data
    });
  }
};

export default createProject;

标签: javascriptreactjsreact-redux

解决方案


useEffect(() => {
if (props.errors) {
  let temp = { ...values };
  temp.errors = props.errors;
  setValues(temp);
}
}, [props.errors]);

使用 react hooks 时,需要获取之前的状态,然后设置新的值。当您仅设置 props.errors 时,它会从您的状态中删除所有其他键值。

希望这可以帮助


推荐阅读