axios 需要有关Redux Toolkit的帮助

cigdeys3  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(144)

形实转换如下所示:

export const registerUser = createAsyncThunk(
  "auth/register",
  async (userData) => {
    try {
      const response = await axios.post(REGISTER_URL, userData);
      return response.data;
    } catch (error) {
      // console.log(error.response.data) the output is provided below
      throw error.response.data;
    }
  }
);

输出量:

{
  "error": "Bad Request",
  "message": [
    "email should not be empty",
    "email must be an email"
  ],
  "statusCode": 400
}

给定这种输出格式,我应该如何在reducer的.addMatcher()中构造state.error更新?

.addMatcher(
  (action) => action.type.endsWith("/rejected"),
  (state, action) => {
    state.loading = false;
    state.error = ?; // What's the appropriate way to structure the error messages?
  }
)
dgiusagp

dgiusagp1#

你可能应该实际上 * 返回 * 一个带错误的被拒绝的Promise,而不是仅仅重新抛出它。有关更多详细信息,请参见处理Thunk错误。
范例:

export const registerUser = createAsyncThunk(
  "auth/register",
  async (userData, thunkAPI) => {
    try {
      const response = await axios.post(REGISTER_URL, userData);
      return response.data;
    } catch (error) {
      // console.log(error.response.data) the output is provided below
      return thunkAPI.rejectWithValue(error.response.data);
    }
  }
);

从这里开始,它将只是在registerUser.rejected操作的payload中。

.addMatcher(
  (action) => action.type.endsWith("/rejected"),
  (state, action) => {
    state.loading = false;
    state.error = action.payload; // or pick out what you need from payload
  }
)

相关问题