錯誤:
Argument of type '(dispatch: Dispatch<ShopDispatchTypes>) => Promise<void>' is not assignable to parameter of type 'AnyAction'.
useEffect(() => {
dispatch(GetShops());
}, []);
我正在嘗試使用 Typescript 實作 redux-thunk。我使用 react、typescript 和 redux-thunk 創建了簡單的購物卡應用程式,但解決了上述問題。下面是我的代碼片段。隨時詢問您是否需要更多資訊。
商店.actionTypes.ts
export const SHOP_LOAD_START = 'SHOP_LOAD_START';
export const SHOP_LOAD_SUCCESS = 'SHOP_LOAD_SUCCESS';
export const SHOP_LOAD_ERROR = 'SHOP_LOAD_ERROR';
export type Shop = {
id: string;
name: string;
};
export type ShopType = {
shops: Shop[];
};
export interface ShopLoadStart {
type: typeof SHOP_LOAD_START;
}
export interface ShopLoadError {
type: typeof SHOP_LOAD_ERROR;
}
export interface ShopLoadSuccess {
type: typeof SHOP_LOAD_SUCCESS;
payload: ShopType;
}
export type ShopDispatchTypes = ShopLoadStart | ShopLoadError | ShopLoadSuccess;
商店.action.ts
export const GetShops = () => async (dispatch: Dispatch<ShopDispatchTypes>) => {
try {
dispatch({
type: SHOP_LOAD_START,
});
const res = await http.get('d9b45894-2549-4e34-9486-7668c2e000a0');
dispatch({
type: SHOP_LOAD_SUCCESS,
payload: res.data,
});
} catch (e) {
dispatch({
type: SHOP_LOAD_ERROR,
});
}
};
商店.reducer.ts
export interface IDefaultState {
isLoading: boolean;
shop?: ShopType;
}
export const defaultState: IDefaultState = {
isLoading: false,
};
const shopsReducer = (
state: IDefaultState = defaultState,
action: ShopDispatchTypes
): IDefaultState => {
switch (action.type) {
case SHOP_LOAD_START:
return {
...state,
isLoading: true,
};
case SHOP_LOAD_SUCCESS:
return {
...state,
isLoading: false,
shop: action.payload,
};
case SHOP_LOAD_ERROR:
return {
...state,
isLoading: false,
};
default:
return state;
}
};
export default shopsReducer;
store.ts
const Store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
export type RootStore = ReturnType<typeof rootReducer>;
export default Store;
購物卡.tsx
const ShoppingCard: React.FC<IShoppingCard> = (props: IShoppingCard) => {
const { label } = props;
const dispatch = useDispatch();
const shopsData = useSelector((state: RootStore) => state.shop);
useEffect(() => {
dispatch(GetShops()); //Getting error here
}, []);
}
如果我做錯了什么,請告訴我。為此花了幾個小時,但沒有找到任何解決方案。
GitHub:源代碼鏈接
uj5u.com熱心網友回復:
問題是const dispatch = useDispatch();只知道核心的基本Dispatch型別redux。該Dispatch型別不知道 thunk 存在——它只接受普通的動作物件。因此,當您嘗試發送 thunk 時,它(正確地)會出錯。
修復方法是遵循我們的“與 TS 一起使用”指南,以便AppDispatch從 中正確推斷型別store.dispatch,然后定義包含 thunk 型別的預型別鉤子:
https://redux.js.org/tutorials/typescript-quick-start
此外,雖然它與問題沒有直接關系:您使用的“手寫” Redux 模式非常過時,而不是我們希望人們今天使用 Redux 的方式。相反,我們現在教授一組更容易學習和使用的“現代 Redux”模式 - Redux Toolkit for logic React-Redux hooks。我們的官方檔案教程今天將 RTK hooks 作為標準 Redux 進行教學,但大多數其他教程都已經過時了。請參閱我們的官方檔案以了解如何使用 Redux Toolkit,這將大大簡化您獲得的代碼:
https://redux.js.org/tutorials/index
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481464.html
標籤:反应 打字稿 还原 反应还原 redux-thunk
上一篇:如何在本機反應中制作通用組件?
