Pag*_*ius 4 reactjs redux react-redux react-hooks redux-toolkit
因此,在 redux 工具包中,您可以创建使用多个端点调用 RestApi 的钩子,我使用 3 个端点,使用 redux-toolkit 创建了 3 个可以在 React 应用程序中的任何位置使用的钩子,我的问题是如何做我让它在一个组件中全部工作?
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 = [], isFetching } = useGetAllQuery();
const { data = [], isFetching } = useGetCountryQuery();
const { data = [], isFetching } = useGetRegionQuery(option);
return (
<>
{data.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;
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我必须为所有三个钩子解构“data”和“isFetching”,这就是我了解函数的方式,我使用所有三个 API 钩子的替代方法是什么,这样我就可以在同一个组件上使用它,即“ CountryCard”我想显示?
其一,你可以决定不解构。
const allResult = useGetAllQuery();
const countriesResult = useGetCountryQuery();
const regionResult= useGetRegionQuery(option);
return (
<>
{countriesResult.data?.map((country) => (
Run Code Online (Sandbox Code Playgroud)
或者,您在解构时重命名事物:
const { data: all = [], isFetching: allFetching } = useGetAllQuery();
const { data: countries = [], isFetching: countryFetching } = useGetCountryQuery();
const { data: regions = [], isFetching: regionFetching } = useGetRegionQuery(option);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1600 次 |
最近记录: |