1

我一直在试图弄清楚为什么标签失效不起作用并添加了一些日志记录。providesTagsin工作正常,getMeinvalidatesTagsinlogin从未被调用。可能有什么问题?

我有一个这样的 redux RTK 查询 API:

const baseQuery = fetchBaseQuery({
  baseUrl: baseUrl,
  prepareHeaders: (headers, { getState }) => {
    const token = getState().auth.token
    if (token) {
      headers.set('authorization', `Bearer ${token}`)
    }
    return headers
  },
})

export const api = createApi({
  baseQuery: baseQuery,
  tagTypes: ['User'],
  endpoints: build => ({
    login: build.mutation({
      query: code => ({
        url: `auth/login/?code=${code}`,
        method: 'POST',
      }),
      invalidatesTags: (result, error, arg) => {
        console.log('auth/login', result, error, arg)
        return ['User']
      },
    }),
    getMe: build.query({
      query: () => 'auth/me',
      providesTags: result => {
        console.log('auth/me', result)
        return ['User']
      },
    }),
  }),
})

export const { useLoginMutation, useGetMeQuery } = api

login当从这样的回调加载页面时,在组件挂载时调用:

const CallbackComponent = () => {
  const location = useLocation()
  const [login, { isUninitialized, isLoading, isError, data, error }] = useLoginMutation()

  useEffect(() => {
    if (isUninitialized) login(getCode(location))
  })
  ...
}

getMe在这样的组件中使用:

const Header = () => {
  const isAuthenticated = useIsAuthenticated()
  const {
    data: user,
    isError,
    error,
  } = useGetMeQuery(null, {
    skip: !isAuthenticated,
  })

  if (isError) return <span>{JSON.stringify(error)}</span>

  return (
    <nav className="header">
      {user ? <CharacterList characters={user.characters} /> : null}
      {!user || user.characters.length === 0 ? <Login /> : null}
    </nav>
  )
}
4

1 回答 1

2

原来问题不在这些地方。我没有将 api 中间件添加到我的商店。

export const store = configureStore({
  reducer: rootReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware().concat(api.middleware),
})

文档:https ://redux-toolkit.js.org/tutorials/rtk-query#add-the-service-to-your-store

于 2021-09-22T08:48:00.820 回答