如何使用 createAsyncThunk 显示拒绝消息?

How to show reject message with createAsyncThunk?

我想在我的 API fetch 抛出错误时显示一条错误消息,但这个错误实际上得到了满足,所以在额外的 reducer 中,被拒绝的部分根本不会被调用。

    export const searchWeather = createAsyncThunk(
      "weather/searchWeather",
      async (apiAddress) => {
        const response = await fetch(apiAddress);
        const data = await response.json();
        return data;
      }
    );

................................................................................

      extraReducers: (builder) => {
        builder
          .addCase(searchWeather.pending, (state) => {
            state.isLoading = true;
            state.hasError = false;
          })
          .addCase(searchWeather.fulfilled, (state, action) => {
            state.weather = action.payload;
            state.isLoading = false;
            state.hasError = false;
          })
          .addCase(searchWeather.rejected, (state) => {
            state.isLoading = false;
            state.hasError = true;
          });
      },

这样即使我得到一个404错误,它仍然得到履行而不是被拒绝。

我所做的是以这种方式将 Promise.reject() 包含在我的异步函数中:

export const searchWeather = createAsyncThunk(
  "weather/searchWeather",
  async (apiAddress) => {
    const response = await fetch(apiAddress);
    if (!response.ok) {
        return Promise.reject();
      }
    const data = await response.json();
    return data;
  }
);

它确实可以正常工作,并显示我在其他地方定义的错误消息。

但我想知道这是否真的是正确的方法,或者是否有更好的解决方案。

这几乎是正确的方法 - fetch 不会 throw 非 2xx 状态代码。

语义可能会有所改变 - 您通常会抛出或 return rejectWithValue:

    if (!response.ok) {
        throw new Error("response was not ok")
      }

    if (!response.ok) {
        return thunkApi.rejectWithValue("response was not okay")
     }