我使用react with redux tookit来调用我的api并将我的响应存储在状态中,但每当我调用async 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
您的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
});
};