javascript - 即使不成功,在 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;
解决方案
useEffect(() => {
if (props.errors) {
let temp = { ...values };
temp.errors = props.errors;
setValues(temp);
}
}, [props.errors]);
使用 react hooks 时,需要获取之前的状态,然后设置新的值。当您仅设置 props.errors 时,它会从您的状态中删除所有其他键值。
希望这可以帮助
推荐阅读
- java - ComboBox ChangeListener 在 AutoCompleteDropDown 中被调用 3 次
- python - 如何在 Django 中正确定义“get_absoute_url”?
- amazon-web-services - 使用 CLI 获取 aws EMR DNS 地址
- c - 陷入无限循环,不知道我做错了什么
- python-3.x - 是否有用于自动从 Google 趋势中提取数据的循环功能?
- reactjs - React Data Grid,如何删除一行?
- python-3.x - 使用python在眼睛图像中检测瞳孔
- regex - 如何使用正则表达式选择最后一次出现的数字而不是 IP 地址,仅从默认 IIS 日志中删除时间
- java - 在键上加入 2 个无界 Pcollections
- python - 如何在基于 Django 类的表单上编辑文本