我有一个Products组件,它向“/api/products”发出GET请求。在后端的路由处理函数中,我抛出了一个错误,并向客户端发送了一条自定义错误消息(“Not Authorized”)。
在客户端,我想显示从服务器发送的自定义错误消息。但是,当我console.log操作对象时,错误消息显示为:'请求失败,状态代码为500'。
如何访问从服务器发回的错误消息?
我在createAsyncThunk中做了一些处理错误的研究。根据文档,我可以用rejectWithValue来处理错误。但是我不知道如何在我的例子中实现它。
代码片段如下所示:
productsSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const initialState = {
status: "idle",
products: [],
error: null,
};
export const fetchProducts = createAsyncThunk(
"products/fetchProducts",
async () => {
const { data } = await axios.get("/api/products");
return data;
}
);
export const productsSlice = createSlice({
name: "products",
initialState,
reducers: {},
extraReducers: {
[fetchProducts.fulfilled]: (state, action) => {
state.status = "succeeded";
state.products = action.payload;
},
[fetchProducts.pending]: (state, action) => {
state.status = "loading";
},
[fetchProducts.rejected]: (state, action) => {
console.log(action);
state.status = "failed";
state.error = action.error.message;
},
},
});
export default productsSlice.reducer;
Products.js
import React, { useEffect } from "react";
import { Row, Col } from "react-bootstrap";
import Product from "./Product";
import { fetchProducts } from "./productsSlice";
import { useDispatch, useSelector } from "react-redux";
const Products = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
const { status, products, error } = useSelector((state) => state.products);
return (
<>
<h1>Latest Products</h1>
{status === "loading" ? (
<h2>Loading...</h2>
) : error ? (
<h3>{error}</h3>
) : (
<Row>
{products.map((product) => (
<Col sm={12} md={6} lg={4} xl={3} key={product._id}>
<Product item={product} />
</Col>
))}
</Row>
)}
</>
);
};
export default Products;
1条答案
按热度按时间ac1kyiln1#
我终于设法使用rejectWithValue实用程序函数访问了从服务器发送的错误消息。
执行return rejectWithValue(errorPayload)操作会导致被拒绝的操作将该值用作action.payload。