【问题标题】:Creating a thunk with arguments. Getting "Parameter 'dispatch' implicitly has an 'any' type"使用参数创建一个 thunk。获取“参数'dispatch'隐式具有'any'类型”
【发布时间】:2021-08-22 01:13:27
【问题描述】:

我对 redux-thunk 非常陌生,尤其是 Typescript 的复杂性。这可能是不需要的信息,但以防万一我想做的是定义一个 thunk 来处理所有 API 请求。为此,我需要有一个 Id 来处理每个请求的状态。 代码是这样的:

export const createRequest: apiRequestActionCreator = (requestId: string) => async (dispatch, getState) => {
//do stuff
dispatch(requestStartedAction(requestId));
try {
    //do stuff
    dispatch(requestSucceededAction(requestId));
} catch (error) {
    //do stuff
    dispatch(requestFailedAction(requestId, error));
}

而 apiRequestActionCreator 是一个返回 ThunkAction 的函数,如下所示:

export type apiRequestActionCreator = () => ThunkAction<void, apiRequestStates, {}, apiRequestAction>

只要我将 requestId 参数添加到 thunk,我就会收到错误 Parameter 'dispatch' implicitly has an 'any' type。 (我没有得到无参数函数的错误)

我不得不假设有办法做到这一点,但我不知道如何。

【问题讨论】:

    标签: typescript react-redux redux-thunk


    【解决方案1】:

    试试这个:

    export const createRequest: apiRequestActionCreator = (requestId: string) =>
     async (dispatch: ThunkDispatch<State, unknown, Actions>, getState) =>
    {
    ...
    }
    

    使用State = apiRequestStatesActions = apiRequestAction

    【讨论】:

      【解决方案2】:

      我也有类似的问题(这是我第一次回答堆栈溢出问题,所以是的)但我所做的是 this return async (dispatch: any) 并且之后似乎工作正常

      【讨论】:

        猜你喜欢
        • 2018-09-23
        • 2018-09-25
        • 2017-11-30
        • 2021-12-24
        • 2021-05-31
        • 2019-03-15
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        相关资源
        最近更新 更多