【问题标题】:What type should be used with async dispatch?异步调度应该使用什么类型?
【发布时间】:2021-08-28 09:09:57
【问题描述】:

我正在使用 React 使用 TypeScript 创建一个项目。 在 loginAction.tsx 的动作文件中,我有这样一行:

export const login = (obj) => async dispatch => {
    dispatch({
        type: LOGIN_REQUEST,
    });
    const response = await axios.post(`/api/login`, obj);
    if (response.data && response.data.status === 'success') {
        dispatch({
            type: LOGIN_SUCCESS,
            payload: response.data
        });
    } else if (response.data && response.data.status === 'failure') {
        dispatch({
            type: LOGIN_FAILURE,
            payload: response.data
        });
    }
}

这在 JavaScript 中运行良好。但是在 TypeScript 中,我不确定应该使用什么返回类型以及如何使用它们。我在某些方面尝试过,但没有一个被接受。每次我在“export const login = (obj) => async dispatch =>”行中遇到错误时。谁能帮我在 TypeScript 中正确编写这部分?

PS:我尝试像这样使用第一行:

interface ILoginObject {
    email: string,
    password: string
}

export const login = (loginObject: ILoginObject) => async dispatch => {}

但它显示“缺少函数返回类型”并通过在“异步调度 =>”部分下划线显示错误。

【问题讨论】:

  • 让我们首先发布您遇到的确切错误:)
  • 返回void。 .
  • 我尝试使用“export const login = (loginObject: ILoginObject) => async dispatch =>”。在那里,我收到一个错误“函数缺少返回类型”。 ILoginObject 是:interface ILoginObject { email: string, password: string }
  • 你能写下第一行加上返回类型吗?我不确定应该在哪里添加“void”返回类型。在“调度”之后添加它不起作用。 @RajdeepDebnath
  • 我对你其他问题的回答应该使这不是问题:stackoverflow.com/a/67943707/10431574 但这里的答案将涉及从 redux-thunk 导入调度类型。

标签: javascript reactjs typescript redux-thunk


【解决方案1】:
interface ILoginObject {
    email: string,
    password: string
}

interface ILoginDispatch {
    type: string,
    payload?: {
        success? : boolean,
        status?: number,
        message?: string,
        user?: {
            id: string,
            email: string
        },
        access_token?: string,
        expires_in?: string
    }
}

export const userLogin = (loginObject: ILoginObject) => async (dispatch: Dispatch<ILoginDispatch>): Promise<void> => {
    dispatch({
        type: LOGIN_REQUEST
    });

    const response = await axios.post(`/api/login`, loginObject);

    if(response.data && response.data.access_token) {
        dispatch({
            type: LOGIN_SUCCESS,
            payload: response.data
        });
    }
    else {
        dispatch({
            type: LOGIN_FAILURE,
            payload: response.data
        });
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多