有一个createAsyncThunk
,我用axios
发出一个请求,如果我执行return res
,并把action.payload.data
传递给pizzas数组,那么一切都正常,但我在控制台得到一个错误:
http://joxi.ru/eAO8VK3CvyXqwr
我明白需要做什么(return res.data
),然后就不会有错误了。
但是我需要返回一些东西return res
,因为我需要从别处的请求中获得res.headers["x-total-count"]
,并将数量传递给itemsCount
export const fetchPizzas = createAsyncThunk("items/fetchPizzasStatus", async (params) => {
const { category, sortBy, order, search, perPage, currentPage } = params;
const res = await axios.get(`http://localhost:3001/items?${category}&q=${search}&_sort=${sortBy}&_order=${order}&_page=${currentPage}&_limit=${perPage}`);
return res;
});
const initialState = {
pizzas: [],
itemsCount: 0,
status: "loading",
};
export const getItemsSlice = createSlice({
name: "items",
initialState,
reducers: {},
extraReducers: {
[fetchPizzas.pending]: (state) => {
state.status = "loading";
state.pizzas = [];
},
[fetchPizzas.fulfilled]: (state, action) => {
state.status = "success";
state.pizzas = action.payload.data;
state.itemsCount = action.payload.headers["x-total-count"];
},
[fetchPizzas.rejected]: (state) => {
state.status = "error";
state.pizzas = [];
},
},
});
1条答案
按热度按时间qnzebej01#
假设API被配置为允许访问所有的响应头,那么我建议在返回解析值之前,在action creator中解压缩你想要/需要的头值。错误是头对象中的某些东西是不可序列化的,比如一个函数。
示例:
也就是说,看起来
itemCount
状态只是pizzas
数组的长度,很容易从现有的状态中派生出来。它很可能不需要也存储在状态中。我建议完全删除它。一个二个一个一个