【问题标题】:I have a weird problem with the Redux Toolkit MERN我对 Redux Toolkit MERN 有一个奇怪的问题
【发布时间】:2022-02-17 04:35:57
【问题描述】:

我在发出 axios 请求时遇到了 redux 工具包的问题。这是我的电话:

export const register = createAsyncThunk(
  'auth/register',
  async (user, thunkAPI) => {
    try {
      return await authService.register(user);
    } catch (error) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

我的 authService 是:

const register = async userData => {
  const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  };
  const { data } = await axios.post('/api/v1/auth/register', userData, config);
  return data;
};

没什么特别的,只是将 API 调用分离到一个单独的文件中。

这是我的 authSlice:

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    reset: state => {
      state.isLoading = false;
      state.isError = false;
      state.isSuccess = false;
      state.message = '';
    },
  },
  extraReducers: {
    [register.pending]: state => {
      state.isLoading = true;
    },
    [register.fulfilled]: (state, action) => {
      state.isLoading = false;
      state.isSuccess = true;
      state.user = action.payload;
    },
    [register.rejected]: (state, action) => {
      state.isLoading = false;
      state.isError = true;
      state.message = action.payload;
      state.user = null;
    },
  },
});

一切都很好,我可以注册一个用户,一切都很好。但是,例如,当我没有向我输入用户名、电子邮件等时,它只是 auth/register/pending,我希望它切换到 auth/register/rejected 以将错误置于状态并显示在前面.在服务器控制台中向我报告错误,如下所示:

(node:7012) UnhandledPromiseRejectionWarning: Error: Please provide all values      
    at register (file:///C:/Users/Uros/Desktop/sn-mern-full/controllers/authController.js:19:11)

没关系,我设置了这个错误消息(请提供所有值)..如何让 register.rejected 将错误传递给 state.message?

【问题讨论】:

    标签: node.js reactjs redux-toolkit


    【解决方案1】:

    您没有发现 axios.post 端点调用的错误:

    const register = async userData => {
    try {
      const config = {
        headers: {
          'Content-Type': 'application/json',
        },
      };
      const { data } = await axios.post('/api/v1/auth/register', userData, config);
      return data;
    } catch(error) {
       Promise.reject(error);
    }};
    

    这样,您将在注册操作的 catch 块中获得服务器的结果,将 register.rejected 操作发送到那里,并将您从服务器收到的错误消息作为有效负载。

    或者更简单,只返回 axios 调用(它本身返回一个 Promise)然后你不需要 try/catch 它,你可以只处理动作中的错误:

    const register = userData => {
      const config = {
        headers: {
          'Content-Type': 'application/json',
        },
      };
      return axios.post('/api/v1/auth/register', userData, config);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-13
      • 2019-04-25
      • 1970-01-01
      • 2021-11-26
      • 2019-10-21
      • 1970-01-01
      • 2021-12-31
      • 2021-04-01
      • 2021-12-22
      相关资源
      最近更新 更多