【问题标题】:How do I hide error(s) after a few seconds? MERN stack几秒钟后如何隐藏错误? MERN 堆栈
【发布时间】:2022-02-15 08:04:41
【问题描述】:

我想知道几秒钟后如何隐藏错误。例如,我有一个必须传递用户名、描述、图像等的 API。所有字段都是必需的,如果缺少一个字段,我会打印错误“所有字段都是必需的”。 NodeJS 为我解决了这个问题。这一切都很好,但我想在 React 中隐藏这个错误片刻之后,如果我转到另一个页面并返回打印错误的那个页面,它仍然存在。在 React 中,我使用 Redux,例如,我的一个操作如下所示:

export const login = (email, password) => async dispatch => {
  try {
    dispatch({ type: USER_LOGIN_REQUEST });

    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };

    const { data } = await axios.post(
      '/api/v1/user/login',
      { email, password },
      config
    );

    dispatch({ type: USER_LOGIN_SUCCESS, payload: data });

    localStorage.setItem('userInfo', JSON.stringify(data));
  } catch (error) {
    console.log(error.response.data.msg);
    dispatch({
      type: USER_LOGIN_FAIL,
      payload: { msg: error.response.data.msg },
    });
  }
};

这是一些最常见的用户日志和在

dispatch({
      type: USER_LOGIN_FAIL,
      payload: { msg: error.response.data.msg },
    });

Prikazujem gresku koja mi se nalazi u error.response.data.msg.

这是我用于该操作的 Reducer:

export const userReducer = (state = {}, action) => {
  switch (action.type) {
    case USER_LOGIN_REQUEST:
      return { ...state, loading: true };
    case USER_LOGIN_SUCCESS:
      return { ...state, loading: false, userInfo: action.payload };
    case USER_LOGIN_FAIL:
      return { ...state, loading: false, error: action.payload.msg };

    case USER_LOGOUT:
      return {};
    default:
      return state;
  }
};

Reducer 返回我在页面上打印的错误。

这可能是一个有点广泛的问题,但我希望有人能帮助我。 :)

【问题讨论】:

    标签: node.js reactjs redux


    【解决方案1】:

    如果您希望离开屏幕后错误消失,您可以尝试在您的状态下重置错误变量,

    // When user leaves screen dispatch action with type of 'RESET_ERROR'
    
    dispatch({
      type: RESET_ERROR,
    });
    
    // Your reducer
    export const userReducer = (state = {}, action) => {
      switch (action.type) {
        ... 
        case RESET_ERROR:
          return {...state, error: undefined}; // or null, whatever is your initialState is
        default:
          return state;
      }
    };
    
    

    但是,起初我建议(假设您没有申请)首先在客户端进行验证。如果 UI 包含任何类型的表单,请选择 formikreact-hook-form,否则手动进行客户端验证,然后最终依赖您的 nodeJS 服务器验证。

    如果您真的想在单独的 redux 状态下显示错误,那么您可以在用户从头开始操作或离开屏幕或任何其他您想要的条件时重置 redux 状态下的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2016-08-07
      • 1970-01-01
      相关资源
      最近更新 更多