我一直在试图弄清楚为什么标签失效不起作用并添加了一些日志记录。providesTags
in工作正常,getMe
但invalidatesTags
inlogin
从未被调用。可能有什么问题?
我有一个这样的 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>
)
}