首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React & Redux -在页面加载时重置错误

React & Redux -在页面加载时重置错误
EN

Stack Overflow用户
提问于 2020-07-02 20:26:39
回答 1查看 31关注 0票数 0

我有一个用React构建的应用程序。有一个仪表板,上面有一个链接Add Education,当单击它时,会加载一个带有表单的新页面。该表单有几个必填字段和一个提交按钮。当用户尝试提交表单时,如果有任何必需的输入尚未填写,则在遗漏的每个输入下都会显示一条错误消息。

我的问题是,当页面被带着错误状态导航离开时,错误仍然存在,并在返回页面时显示出来。我希望在页面离开时将错误重置为空对象{}。

我使用Redux和React Router。相关代码如下(缩写,..表示不相关),如果有帮助,可以添加更多详细信息,谢谢。

在dashboard/ProfileActions.js中

代码语言:javascript
运行
复制
  ..
  <Link to="/add-education" className="btn btn-light">
    <i className="fas fa-graduation-cap text-info mr-1" />
    Add Education
  </Link>
  ..

在AddEducation.js中

代码语言:javascript
运行
复制
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中

代码语言:javascript
运行
复制
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中

代码语言:javascript
运行
复制
const initialState = {};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_ERRORS:
      return action.payload;
    case CLEAR_ERRORS:
      return {};
    default:
      return state;
  }
}
EN

Stack Overflow用户

发布于 2020-07-02 20:34:03

您可能正在寻找类似以下内容的内容

代码语言:javascript
运行
复制
    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
    }

  }, []);

您可以根据需要放置重置逻辑。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62696296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档