reactjs - React & Redux - 页面加载时重置错误
问题描述
我有一个用 React 构建的应用程序。有一个仪表板,上面有一个链接,添加教育,单击该链接时会加载一个带有表单的新页面。该表单有几个必填字段和一个提交按钮。当用户尝试提交表单时,如果未填写任何必需的输入,则会在每个丢失的输入下方显示错误消息。
我的问题是,当页面导航离开状态错误时,错误仍然存在并在返回页面时显示。我希望在离开页面时将错误重置为空对象 {}。
我使用 Redux 和 React 路由器。相关代码如下(缩短,.. 表示不相关),如果有帮助,可以添加更多详细信息,谢谢。
在仪表板/ProfileActions.js
..
<Link to="/add-education" className="btn btn-light">
<i className="fas fa-graduation-cap text-info mr-1" />
Add Education
</Link>
..
在 AddEducation.js
function AddEducation(props) {
const [eduState, setEduState] = useState({
school: '',
..,
errors: {},
});
useEffect(() => {
setEduState({
...eduState,
errors: props.errors,
});
}, [props.errors]);
const onSubmit = (e) => {
e.preventDefault();
const eduData = {
school: eduState.school,
..
};
props.addEducation(eduData, props.history);
};
const onChange = (e) => {
setEduState({
...eduState,
[e.target.name]: e.target.value,
});
};
return (
<div className="add-education">
..
<Link to="/dashboard" className="btn btn-light">
Go Back
</Link>
..
<form onSubmit={onSubmit}>
<TextFieldGroup
placeholder="* School"
name="school"
value={eduState.school}
onChange={onChange}
error={eduState.errors.school}
/>
..
在 profileActions.js
export const addEducation = (eduData, history) => (dispatch) => {
dispatch(clearErrors());
axios
.post('/api/profile/education', eduData)
.then((res) => history.push('/dashboard'))
.catch((err) => {
dispatch({
type: GET_ERRORS,
payload: err.response.data,
});
});
};
..
export const clearErrors = () => {
return {
type: CLEAR_ERRORS,
};
};
在errorReducer.js中
const initialState = {};
export default function(state = initialState, action) {
switch (action.type) {
case GET_ERRORS:
return action.payload;
case CLEAR_ERRORS:
return {};
default:
return state;
}
}
解决方案
你可能正在寻找这样的东西
useEffect(() => {
// I'll run when the component is mounted
// Setting the initial state for this component
return () => {
// all the clean-ups related to this component
// I'll run when the component is unmounted
}
}, []);
您可以根据需要放置复位逻辑。
推荐阅读
- reactjs - 无法将 api 和个人输入放入一个对象数组中,并且我的 datamap.map 无法呈现
- mysql - Mysql 错误 2003 (HY00):在 Windows 10 上重启机器后无法连接到服务器
- react-grid-layout - 如何在不使用 React 的情况下恢复 react-grid-layout 的布局
- string - 如何检查子字符串是否在 Postgres 中的任何数组值中?
- blazor - 是否可以在 abp.io 框架中替换 Blazor 的基本组件集以使用 MudBlazor?
- reactjs - React 一键提交具有不同功能的多个表单
- swift - 定义状态变量后以编程方式推送视图
- python - 熊猫中的“放大设置”行为
- javascript - 如何使用 React 高阶函数最大化可组合性?
- javascript - 如何在 javascript 中编写公式并使用 html 显示公式并显示结果?