reactjs 如何从createAsyncThunk axios获取头文件和数据

f45qwnt8  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(157)

有一个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 = [];
    },
  },
});
qnzebej0

qnzebej01#

假设API被配置为允许访问所有的响应头,那么我建议在返回解析值之前,在action creator中解压缩你想要/需要的头值。错误是头对象中的某些东西是不可序列化的,比如一个函数。
示例:

export const fetchPizzas = createAsyncThunk(
  "items/fetchPizzasStatus",
  async ({ category, sortBy, order, search, perPage, currentPage }) => {
    const { data, headers } = await axios.get(`http://localhost:3001/items?${category}&q=${search}&_sort=${sortBy}&_order=${order}&_page=${currentPage}&_limit=${perPage}`);

    const itemCount = headers["x-total-count"];

    return { data, itemCount };
  }
);
const initialState = {
  pizzas: [],
  itemsCount: 0,
  status: "loading",
};

export const getItemsSlice = createSlice({
  name: "items",
  initialState,
  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.itemCount;
    },
    [fetchPizzas.rejected]: (state) => {
      state.status = "error";
      state.pizzas = [];
    },
  },
});

也就是说,看起来itemCount状态只是pizzas数组的长度,很容易从现有的状态中派生出来。它很可能不需要也存储在状态中。我建议完全删除它。
一个二个一个一个

相关问题