這是一個與redax一起使用的動作函數(shù)(它完美地工作,因?yàn)槲沂褂昧怂?/p>
export const fetchCategory = () => { return async (dispatch) => { try { dispatch(settingsSlice.actions.settingsFetching()); const response = await request("/category/getAll", "POST", {}); dispatch(settingsSlice.actions.settingsFetchingSuccess(response)); } catch (e) { dispatch(settingsSlice.actions.settingsFetchingError(e)); } }; };
當(dāng)按鈕被按下時,我需要向伺服器發(fā)出請求並更新狀態(tài)
這是當(dāng)您點(diǎn)擊按鈕時執(zhí)行的函數(shù):
const buttonHandler = async () => { await request("/category/create", "POST", { newCategory: { label: form.categoryLabel, limit: form.categoryLimit, }, }); setForm(initialState); fetchCategory(); };
我已經(jīng)檢查過,表單已經(jīng)發(fā)送到後端,除了"fetchCategory"之外,一切正常
我已經(jīng)嘗試使用useEffect來解決這個問題
useEffect(() => { fetchCategory(); }, [Button , buttonHandler]);
我嘗試安裝不同的依賴項(xiàng),但沒有結(jié)果。如何解決這個問題?
你需要 dispatch
這個動作!
你的 fetchCategory
函式是一個 "thunk action creator"。呼叫 fetchCategory()
會建立一個 thunk 動作,但不會對其執(zhí)行任何操作。你需要呼叫 dispatch(fetchCategory())
來執(zhí)行這個動作。
const buttonHandler = async () => { await request("/category/create", "POST", { newCategory: { label: form.categoryLabel, limit: form.categoryLimit, }, }); setForm(initialState); --> dispatch(fetchCategory()); <-- };