我已经成功获取了我的React / Redux应用程序以从REST API后端检索数据。我正在使用Redux Toolkit的createAsyncThunk功能,该功能会自动设置reducer,当HTTP fetch promise成功或失败时,将调用reducer。
对于这个特定的端点,我希望Redux存储在遇到HTTP 404 Not Found时反射(reflect)一个错误。目前还没有发生。下面显示的组件始终返回“已成功加载”。如何使其显示“错误”呢?
我了解fetch doesn't resolve with an error on HTTP 4xx errors,我需要自己检查响应代码并将其解决为失败。我不明白的是在下面的代码中在哪里或如何执行此操作。我在概念上难以理解异步/等待,这是Redux Toolkit的新手,并且下面的代码已经非常难以调整我的大脑。救命?
这是我的完整代码:
功能/recipeList/recipeListApi.js
export default async function recipeListApi(localApiKey) {
const response = await fetch('https://httpstat.us/404');
const responseJson = await response.json();
return responseJson;
}
功能/recipeList/recipeListSlice.js import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import recipeListApi from "./recipeListApi";
const sliceName = "recipeList";
const initialState = {
loading: false,
error: null,
data: null
};
export const fetchRecipeList = createAsyncThunk("recipeList/fetchRecipeList", async (thunkAPI) => {
const response = await recipeListApi();
return JSON.stringify(response);
});
const recipeListSlice = createSlice({
name: sliceName,
initialState: initialState,
extraReducers: {
[fetchRecipeList.pending]: state => {
if (!state.loading) {
state.loading = true;
}
},
[fetchRecipeList.fulfilled]: (state, action) => {
if (state.loading) {
state.loading = false;
state.data = action.payload;
}
},
[fetchRecipeList.rejected]: (state, action) => {
if (state.loading) {
state.loading = false;
state.error = action.payload;
}
}
}
});
export const recipeListReducer = recipeListSlice.reducer;
组件/RecipeList.js import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchRecipeList } from '../features/recipeList/recipeListSlice';
export const RecipeList = () => {
const recipeList = useSelector(state => state.recipeList);
const dispatch = useDispatch();
/* Equivalent to componentDidMount() */
useEffect(() => {
dispatch(fetchRecipeList());
}, []);
return <>
{recipeList.loading && <h1>Loading</h1>}
{!recipeList.loading && recipeList.error !== null && <h1>Error</h1>}
{!recipeList.loading && recipeList.error === null && <h1>Loaded successfully</h1>}
</>;
}
最佳答案
检查响应是否具有ok状态-或您想检查response
的任何条件-并返回拒绝的 promise ,如下所示:
export default async function recipeListApi(localApiKey) {
const response = await fetch('https://httpstat.us/404');
if(!response.ok) {
return Promise.reject();
}
return await response.json();
}