如何在同一个React组件中使用多个Redux Toolkit Query钩子?
解决方案
你遇到的是解构时的变量命名冲突问题,直接在解构的时候对data和isFetching做别名重命名即可,这也是这类场景的标准处理方案,写法为const { data: 自定义别名, isFetching: 自定义别名 } = 钩子调用。
修改后的完整代码如下:
import React from "react"; import { useSelector } from "react-redux"; import { useGetCountryQuery, useGetRegionQuery, useGetAllQuery } from "../../services/CountryAPI"; import CountryCard from "./CountryCard"; import { Link } from "react-router-dom"; const CountryList = () => { const { option } = useSelector((state) => state.option); // 解构时重命名,避免变量冲突 const { data: allCountries = [], isFetching: loadingAll } = useGetAllQuery(); const { data: countryList = [], isFetching: loadingCountry } = useGetCountryQuery(); const { data: regionCountries = [], isFetching: loadingRegion } = useGetRegionQuery(option); // 这里可以根据业务逻辑选择要渲染的数据源,示例为根据option切换 const renderData = option === 'all' ? allCountries : option === 'country' ? countryList : regionCountries; const isLoading = loadingAll || loadingCountry || loadingRegion; if (isLoading) return <div>加载中...</div>; return ( <> {renderData.map((country) => ( <Link onClick={() => {}} key={country.name.official} to={`/details/${country.name.official}`} > <CountryCard key={country.name.official} name={country.name.official} capital={country.capital} region={country.region} population={country.population} flag={country.flags.svg} /> </Link> ))} </> ); }; export default CountryList;
补充说明:
- 如果你需要同时展示三个接口的所有数据,直接分别遍历
allCountries、countryList、regionCountries三个数组即可 - 加载状态可以根据业务需要单独控制某一个接口的加载态,也可以像示例一样合并判断所有接口的加载状态
- 这种重命名是ES6的标准解构特性,所有需要解构多个同名字段的场景都可以用这个方法解决
内容的提问来源于stack exchange,提问作者Pavelion
相关产品推荐
相关产品推荐

