RTK 查询无法在 React(使用 TS)挂钩 "MultiBrandAPI.myMutation" 中有条件地调用 hander 上的突变。”

RTK Query unable to use mutation on hander in react React (with TS) hook "MultiBrandAPI.myMutation" is called conditionally."

所以我们正在迁移到 RTK 查询。我们已经能够毫无问题地进行查询。但是现在我们正在尝试做一个POST,并且发生了以下问题。

这是我在 component.tsx 文件中的函数:

const [postToken] = MultiBrandAPI.useNewPartnerTokenPostMutation();

const handleNavigateToPartner = async(partner: Partner) => {

    const auth = SessionSlice.getInitialState().token;
    try {
        const result = await postToken({
            id: partner.id,
            token: auth
        }).unwrap();
        console.log(result);
    } catch (err) {
        console.log(err);
    }
};

这是我的 api.ts 文件:

import {Partner} from '@libs/partner';
import {createApi} from '@reduxjs/toolkit/query/react';

import {BaseQueryWithAuth} from '../redux/rtk-query';

interface PostObject {
    id: string,
    token: string | undefined
}

export default createApi({
    reducerPath: 'multiBrandAPI',
    baseQuery: BaseQueryWithAuth,
    endpoints: (builder) => ({
        newPartnerTokenPost: builder.mutation<string, PostObject>({
            query: ({id, token}: PostObject) => ({
                url: `u/${id}/token`,
                method: 'POST',
                body: `Authorization ${token}`
            }),
            invalidatesTags: [{type: 'Partners', id: 'LIST'}],
        }),
        getAllPartners: builder.query<Partner[], void>({
            query: () => ({url: 'auth/login'}),
            providesTags: () => {
                return [{type: 'Partners'}];
            }
        }),
    }),
    tagTypes: ['Partners']
});

我在控制台上收到此错误:

React Hook "MultiBrandAPI.useNewPartnerTokenPostMutation" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return? react-hooks/rules-of-hooks Blockquote

这与制作 POST 无关 - 您只是违反了钩子规则。

您必须在根级别(不是在任何回调中)的组件函数中调用 useNewPartnerTokenPostMutation,而不是在 if/else 块内部和任何可能的 return 语句之前。 React 中的任何其他钩子也是如此。