【发布时间】:2021-06-29 09:35:20
【问题描述】:
所以我有一个 SPFx webpart(使用打字稿)并添加了 Redux。现在一切正常,但是需要键入 thunk 函数,我不知道如何键入它们。
所以这是我要调度的操作:
export const setListByMiddelware:any = (listId:string) => (dispatch, getState) => {
dispatch(listIdAdded(listId));
dispatch(spApiCallBegan({
method: GET_LIST_ITEMS,
options: {
listId
},
onSuccess: itemsAdded.type
}));
}
这是执行 SP 调用的 SharePoint 中间件:
import SP from '../../services/SharePointService';
import * as actions from '../SP_API';
const api = store => next => async action => {
if(action.type !== actions.spApiCallBegan.type) {
next(action);
return;
}
const { method, options, onSuccess, onError, onStart } = action.payload;
if(onStart) {
store.dispatch({ type: onStart });
}
next(action);
try {
const result = await SP[method](options);
store.dispatch(actions.spApiCallSuccess(result));
if(onSuccess) {
store.dispatch({
type: onSuccess,
payload: result
});
}
} catch(ex) {
store.dispatch(actions.spApiCallFailed(ex.message));
if(onError) {
store.dispatch({
type: onError,
payload: ex.message
});
}
}
}
export default api;
现在你可以看到我通过简单地将 thunk 输入到any 解决了这个问题,并且效果很好,但我想强烈输入它,因为这些是我的组件的功能实际使用。
这是我正在使用的堆栈:
redux@4.0.5
react-redux@7.2.3
@reduxjs/toolkit@1.5.1
我在输入 Redux 时遇到了真正的麻烦,正如你所看到的,我或多或少地放弃了这一点,而谷歌在这方面并没有多大帮助。因此,我的 Redux 代码大部分是无类型的。
至于打字稿,我想我使用的是 TS 3.3 自带的 SPFx 1.11.0,我使用的是 SPFx 版本。
编辑
正如 markerikson 所指出的那样,我已经阅读了有关在此处输入 Redux 的官方 Redux 文档:
https://redux.js.org/recipes/usage-with-typescript#type-checking-middleware
但是当我实现它时,我得到:Type '(listId: string) => (dispatch: any, getState: any) => void' is notassignable to type 'ThunkAction
这是我正在使用的商店设置:
import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import listRedurcer, { IListSate} from './lists';
import SP_API from './middleware/SP_API';
const store = configureStore({
reducer: listRedurcer,
middleware: [
...getDefaultMiddleware(),
SP_API
],
devTools : {
name: 'ReduxList'
}
});
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
export default store;
对于 thunk,我也使用了这个 ThunkAction<void, RootState, string, AnyAction>,但我得到了同样的错误。
【问题讨论】:
标签: typescript redux