简体   繁体   English

使用Typescript将Thunk分发到商店

[英]Dispatching Thunk to the store with Typescript

In my main store.ts I have this: 在我的主要store.ts中,我有这个:

 const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); 

So on the first render it dispatches and action to fetchUser to see if he/she can see the content. 因此,在第一个渲染器上,它向fetchUser调度并执行操作,以查看他/她是否可以看到内容。

This is the thunk: 这是重击:

 export const fetchUser = (): ThunkAction< void, TRootState, null, Action > => async dispatch => { const response = await axios.get(GET_USER_INFORMATION); dispatch({ type: FETCH_USER, payload: response.data }); }; 

But Typescript throws an error: 但是Typescript抛出错误:

 src/store/index.ts (14,16): Argument of type 'ThunkAction<void, { userReducer: any; }, null, Action<any>>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type 'ThunkAction<void, { userReducer: any; }, null, Action<any>>'. 

store/index.ts line 14: store / index.ts第14行:

store.dispatch(fetchUser())

Honestly, I'm lost. 老实说,我迷路了。 How can I fix that? 我该如何解决? I don't want to type 'any' in the thunk. 我不想在thunk中输入“ any”。

store.dispatch only accepts an action, not function. store.dispatch仅接受一个动作,而不接受功能。 but the thunk overrides it. 但重击将其覆盖。 you need to specify the thunk type. 您需要指定转换类型。

try this 尝试这个

composeWithDevTools(applyMiddleware(thunk as ThunkMiddleware<RootState, RootAction>))

also, check this official docs 另外,请查看此官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM