【问题标题】:React & Redux - Resetting errors when a page loadsReact & Redux - 页面加载时重置错误
【发布时间】:2020-07-02 12:26:38
【问题描述】:

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

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

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

在仪表板/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;
  }
}

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    您可能正在寻找类似的东西

        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
        }
    
      }, []);
    

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

    【讨论】:

    • 我尝试使用带有清理功能的 useEffect。问题是,一旦 props 填充了错误,它们似乎永远不会离开,并且状态中的错误总是被覆盖。
    • 您从道具中获取错误值。在我上面提到的useEffect 钩子的返回中调度clear error action。
    猜你喜欢
    • 2016-09-14
    • 2018-10-21
    • 2019-05-17
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多