我是 Redux 和 RTK 查询的新手,我不明白当另一个端点响应成功时如何从另一个端点获取数据。
我创建了一个这样的 API:
import { Config } from '@/Config'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
const baseQuery = fetchBaseQuery({ baseUrl: Config.API_URL })
const baseQueryWithInterceptor = async (args, api, extraOptions) => {
let result = await baseQuery(args, api, extraOptions)
if (result.error && result.error.status === 401) {
// Deal with unauthorised
}
return result
}
export const api = createApi({
baseQuery: baseQueryWithInterceptor,
endpoints: () => ({}),
})
我为每种资源都有一个模块,例如:
// /modules/matches
import { api } from '../../api'
import { fetchMatches } from '@/Services/modules/matches/fetchMatches'
export const matchApi = api.injectEndpoints({
endpoints: build => ({
fetchMatches: fetchMatches(build),
}),
overrideExisting: false,
})
export const { useFetchMatchesQuery } = matchApi
// /modules/matches/fetchMatches
export const fetchMatches = build => {
return build.query({
query: type => ({ url: `matches/${type}` })
})
}
因此,在我的组件中,我使用以下方式调用它:
const { data: matches, error, isLoading } = useFetchMatchesQuery('explorer')
现在,当 useFetchMatchesQuery
成功时我需要做的是:
- 使用
useFetchMatchesQuery
响应数据中的所有比赛 ID 创建一个数组 - 调用其他查询以获取参数中包含
matchsIds
的其他数据 - 在呈现
匹配
数据的同一组件中使用响应。
最佳答案
这里的主要选项是在同一组件中拥有第二个 useSomeOtherQuery()
Hook ,但“跳过”该查询,直到第一个查询完成。这可以通过传递 {skip: false}
作为选项,或将 skipToken
变量作为查询参数来完成:
https://redux-toolkit.js.org/rtk-query/usage/conditional-fetching
关于javascript - React Native & RTK 查询 - 请求成功时调用另一个端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70316568/