问题
I have an app built with React. There is a dashboard with a link on it, Add Education, that when clicked loads a new page with a form. The form has several mandatory fields and a Submit button. When a user tries to submit the form, if any of the required inputs has not been filled, an error message shows under each input that was missed.
My problem is that when the page is navigated away from with errors in state, the errors persist and are shown when returning to the page. I'd like for the errors to be reset to empty object {} whenever the page is left.
I use Redux and React Router. The relevant code is below (shortened, .. indicates not relevant), can add further details if it will help, thanks.
in dashboard/ProfileActions.js
..
<Link to="/add-education" className="btn btn-light">
<i className="fas fa-graduation-cap text-info mr-1" />
Add Education
</Link>
..
in 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}
/>
..
in 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,
};
};
in 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;
}
}
回答1:
You might be looking for something like this
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
}
}, []);
You can place your reset logic as required.
来源:https://stackoverflow.com/questions/62696296/react-redux-resetting-errors-when-a-page-loads