所以我在 redux 中有一個異步 thunk 函式:
export const fetchItem = createAsyncThunk('item/fetchItem', async (id: number) => {
const res = await fetch(`${apiUrl}/${id}`)
.then(res => res.json())
return res
})
這是我在 React 中的獲取函式,它通過事件目標(標簽)的 html id 獲取專案:
const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => {
useAppDispatch(fetchItem(e.target.id))
}
錯誤在 fetchItem 中,它說:預期 0 個引數,但得到 1 個。我什至嘗試使用:
useAppDispatch(fetchItem(1))
并得到了同樣的錯誤。
useAppDispatch 看起來像這樣:
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch} from "./redux/store";
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector()
export const useAppDispatch = () => useDispatch<AppDispatch>()
uj5u.com熱心網友回復:
useAppDispatch是一個鉤子,只能直接在組件體內使用useAppDispatch接受 0 個引數,但你傳遞 1useAppDispatch回傳一個dispatch你想使用的函式
// inside your component
const dispatch = useAppDispatch()
const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => {
dispatch(fetchItem(e.target.id))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533608.html
