我正在尝试使用 redux 工具包获取一些数据,但它不起作用。我只是不断收到错误
TypeError: Cannot read property 'type' of undefined
。我正确设置了商店,因为我有其他减速器工作正常。但是当我尝试异步或获取数据时,我遇到了这个问题
错误:
App.js:
代码停在
const actionResult = await dispath(getLiveContest())
,之后不再控制台记录任何内容。
const dispatch = useDispatch();
useEffect(() => {
const fetchLiveContest = async () => {
try {
console.log(1);
const actionResult = await dispatch(getLiveContest());
console.log(2);
const liveContest = unwrapResult(actionResult);
console.log(liveContest);
} catch (error) {
console.log("Failed to fetch live contest: ", error);
}
};
fetchLiveContest();
}, []);
GetLiveContest():
这是该函数的代码。我尝试了
return {name: 'lala'}
但它仍然给了我类型错误
export const getLiveContest = createAsyncThunk(
"contests/fetchLive",
async (params, thunkAPI) => {
console.log(thunkAPI, "thunkAPI");
console.log(params);
const liveContest = await axios ...
return liveContest;
}
);
幻灯片代码:
export const liveContestSlide = createSlice({
name: "live",
initialState: {
contest: [],
loading: "idle",
},
reducers: {},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[getLiveContest.fulfilled]: (state, action) => {
// Add contest to the state array
state.contest.push(action.payload);
},
},
});
我遵循了 redux 工具包文档。我还检查了 stackoverflow 上的其他问题,但仍然无法修复错误,请帮忙
我只是将
import getLiveContest from "./contestSlice";
更改为 import { getLiveContest } from "./contestSlice";
就可以了,结果我只是导入了错误的函数
Alors salut, je pense que la fonction extraReducers fonctionne uniquement avec la méthode createAsyncThunk fournit dans le toolkit reducer.
pour créer il faut :
extraReducers: (builder) => {
builder.addCase(getLiveContest.fulfilled, (state, action) => {
//......
});
},
ensuite le wrapper avec comme ceci :
const getLiveContest = createAsyncThunk("", async ()=>{});