【问题标题】:getting undefined in thunk response在 thunk 响应中变得未定义
【发布时间】:2022-01-03 10:29:41
【问题描述】:

我正在使用 react with redux takeit 来调用我的 api 并将我的响应存储在状态中,但是每当我调用异步 thunk 时,我都会得到未定义的响应,但我在 api 中记录了我的响应,我得到了预期回应,我不知道,因为我是redux的初学者,有人可以帮我解决我做错了什么。下面是我的内存片缩减器

import { RecentPublishedApi } from "../../components/api/api";

export const fetchMemoryAsync = createAsyncThunk(
  "memory/recentPublishedApi",
  async (obj) => {
    const response =await RecentPublishedApi(obj);
    console.log("i am inside the thunk",response)
    return response;
  }
);
const initialState = {
  data: [],
  status: "",
};

export const MemorySlice = createSlice({
  name: "memory",
  initialState,
  reducers: {
  },
  extraReducers: {
    [fetchMemoryAsync.pending]: (state) => {
      state.status = "loading";
    },
    [fetchMemoryAsync.fulfilled]: (state, action) => {
      console.log("fulfilled")
      state.status = "idle";
      console.log(action)
      state.data=action.payload;
    },
    [fetchMemoryAsync.rejected]: (state, action) => {
      state.status = "failed";
      state.error = action.payload;
    },
  },
});

export const selectData = (state) => state.memory.data;

export default MemorySlice.reducer;

我的代码沙盒链接-https://codesandbox.io/s/hidden-snowflake-px34f?file=/src/App.js

【问题讨论】:

    标签: reactjs react-redux redux-toolkit


    【解决方案1】:

    你的 redux-thunk 看起来不错,这是你的 api 函数。

    axios.post 已经返回了一个 Promise,因此将它全部包装在一个 Promise 中只会返回一个 Promise 内的 Promise。

    import axios from "axios";
    
    export const RecentPublishedApi = async (data) => {
      const headers = {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": "e7lwcn_OBGJuu2QsIA8auXzsvi9RGlzueRGDDwVsSKU"
      };
    
      return axios
        .post("https://public.cuebackqa.com/api/timeline/list", data, {
          headers: headers
        })
        .then((res) => {
          return res.data;
        })
        .catch((err) => {
          //throw an application exception
        });
    };
    
    

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 1970-01-01
      • 2020-06-11
      • 2018-03-15
      • 2021-09-13
      • 1970-01-01
      • 2018-02-07
      • 2018-03-11
      • 1970-01-01
      相关资源
      最近更新 更多