使用 React Hooks 在组件间传递数据:构建可复用的数据获取逻辑

12次阅读

使用 React Hooks 在组件间传递数据:构建可复用的数据获取逻辑

本文旨在解决 React 应用中组件间数据传递的问题,尤其是在使用 React Router 进行页面跳转时。我们将探讨如何通过自定义 Hook 来封装数据获取逻辑,并在不同组件中复用,从而避免数据丢失和提高代码的可维护性。通过实例代码和详细解释,你将学会如何有效地在 Country.js 组件和 Details.js 页面之间传递国家信息。

利用自定义 Hook 封装数据获取

在 React 应用中,直接通过 useLocation 传递数据,尤其是在页面刷新或直接访问 Details.js 路由时,可能会导致数据丢失。一个更健壮的方案是创建一个自定义 Hook 来负责获取国家数据。

首先,创建一个名为 useCountry.js 的文件,并定义一个名为 useCountry 的 Hook:

// useCountry.js import { useState, useEffect } from 'react';  function useCountry(countryName) {   const [countryData, setCountryData] = useState(null);   const [loading, setLoading] = useState(true);   const [error, setError] = useState(null);    useEffect(() => {     async function fetchCountryData() {       setLoading(true);       try {         const response = await fetch(`https://restcountries.com/v3.1/name/${countryName}`);         if (!response.ok) {           throw new Error(`HTTP error! status: ${response.status}`);         }         const data = await response.json();         if (data && data.length > 0) {           setCountryData(data[0]); // Assuming the API returns an array, we take the first element         } else {           setError('Country not found');         }       } catch (e) {         setError(e.message);       } finally {         setLoading(false);       }     }      if (countryName) {       fetchCountryData();     } else {       setError('Country name is required');       setLoading(false);     }   }, [countryName]);    return { countryData, loading, error }; }  export default useCountry;

这个 Hook 接收一个 countryName 作为参数,然后使用 useEffect 发起 API 请求,获取特定国家的数据。它返回包含 countryData、loading 和 error 三个属性的对象,分别表示国家数据、加载状态和错误信息。

在 Country.js 组件中使用

在 Country.js 组件中,不再直接传递数据,而是传递国家名称:

// Country.js import React from 'react'; import { Link } from 'react-router-dom';  function Country(props) {   const { name, img, alt, reg, cap, pop } = props;   return (     <Link to={`/details/${name}`}> {/* Pass the country name in the URL */}       <div className='w-72 h-80 shadow bg-white rounded-sm mx-auto cursor-pointer'>         <img className='w-full h-1/2 rounded-sm' src={img} alt={alt} />         <div className='pt-3 pl-4'>           <h3 className='font-extrabold pb-2 pt-1 text-darkBlue'>{name}</h3>           <p className='text-sm text-darkBlue font-bold'>population:             <span className='text-lightDarkGray font-normal'>{pop}</span></p>           <p className='text-sm text-darkBlue font-bold'>region:             <span className='text-lightDarkGray font-normal'>{reg}</span></p>           <p className='text-sm text-darkBlue font-bold'>capital:             <span className='text-lightDarkGray font-normal'>{cap}</span></p>         </div>       </div>     </Link>   ); }  export default Country;

这里关键的改变是将 Link 的 to 属性修改为使用模板字符串,将国家名称 name 作为 URL 的一部分传递,例如 /details/France。

使用 React Hooks 在组件间传递数据:构建可复用的数据获取逻辑

即构数智人

即构数智人是由即构科技推出的AI虚拟数字人视频创作平台,支持数字人形象定制、短视频创作、数字人直播等。

使用 React Hooks 在组件间传递数据:构建可复用的数据获取逻辑36

查看详情 使用 React Hooks 在组件间传递数据:构建可复用的数据获取逻辑

在 Details.js 页面中使用

在 Details.js 页面中,使用 useParams Hook 获取 URL 中的国家名称,并将其传递给 useCountry Hook:

// Details.js import React from 'react'; import Navbar from './components/Navbar'; import { useParams } from 'react-router-dom'; import useCountry from './useCountry'; // Import the custom hook  function Details() {   const { countryName } = useParams(); // Get the country name from the URL   const { countryData, loading, error } = useCountry(countryName); // Use the custom hook    if (loading) {     return <p>Loading country details...</p>;   }    if (error) {     return <p>Error: {error}</p>;   }    if (!countryData) {     return <p>Country not found</p>;   }    return (     <>       <Navbar />       <h1>Details</h1>       <div>         <h2>{countryData.name.common}</h2>         <p>Population: {countryData.population}</p>         {/* Display other country details here */}       </div>     </>   ); }  export default Details;

这里,useParams Hook 用于获取 URL 中的 countryName 参数。然后,将 countryName 传递给 useCountry Hook,获取国家数据。根据 loading、error 和 countryData 的状态,渲染不同的内容。

配置路由

确保你的路由配置正确,以便能够匹配 /details/:countryName 这样的 URL:

// main.js import React from 'react'; import ReactDOM from 'react-dom/client'; import app from './App'; import './index.css'; import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import Details from './Details';  const router = createBrowserRouter([   {     path: "/",     element: <App />,   },   {     path: "/details/:countryName", // Add the countryName parameter     element: <Details />,   }, ]);  ReactDOM.createRoot(document.getElementById("root")).render(   <React.StrictMode>     <RouterProvider router={router} />   </React.StrictMode> );

总结

通过使用自定义 Hook,我们成功地将数据获取逻辑封装起来,并在不同的组件中复用。这种方法不仅解决了数据传递的问题,还提高了代码的可维护性和可测试性。

注意事项:

  • 确保 API 请求的 URL 是正确的,并且能够返回所需的数据。
  • 在处理 API 响应时,要考虑各种情况,例如请求失败、数据为空等。
  • 根据实际需求,可以对自定义 Hook 进行扩展,例如添加缓存机制、错误重试等。
  • 使用 useParams 时,确保路由配置正确,并且 URL 参数的名称与路由配置中的参数名称一致。

css react js json app ai 路由 数据丢失 red 封装 Error 字符串 JS 对象 router

text=ZqhQzanResources