gpt4 book ai didi

javascript - 使用 Redux Toolkit 异步 REST API 模式时如何捕获 HTTP 4xx 错误?

转载 作者:行者123 更新时间:2023-12-03 07:13:10 26 4
gpt4 key购买 nike

我已经成功地让我的 React/Redux 应用程序从 REST API 后端检索数据。我正在使用 createAsyncThunk Redux Toolkit 的特性,它会自动设置在 HTTP fetch promise 成功或失败时调用的 reducer。
对于这个特定的端点,我希望 Redux 存储在遇到 HTTP 404 Not Found 时反射(reflect)错误​​。目前没有发生这种情况。下面显示的组件总是返回“加载成功”。我怎样才能让它显示“错误”?
我明白 fetch doesn't resolve with an error on HTTP 4xx errors ,并且我需要自己检查响应代码并将其解决为失败。我不明白的是在下面的代码中在哪里或如何做到这一点。我在概念上很难理解 async/await,我是 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 for - 并返回一个被拒绝的 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();
}

关于javascript - 使用 Redux Toolkit 异步 REST API 模式时如何捕获 HTTP 4xx 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63211930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com