
本文旨在解决 React 应用中组件间数据传递的问题,尤其是在使用 React Router 进行页面跳转时。我们将探讨如何通过自定义 Hook 来封装数据获取逻辑,并在不同组件中复用,从而避免数据丢失和提高代码的可维护性。通过实例代码和详细解释,你将学会如何有效地在 Country.js 组件和 Details.js 页面之间传递国家信息。
在 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
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。
Flex是一个基于组件的开发框架,可以生成一个由Flash Player运行的富互联网应用程序。Flex将基于标准的语言和各种可扩展用户界面及数据访问组件结合起来,使得开发人员能够构建具有丰富数据演示、强大客户端逻辑和集成多媒体的应用程序。 Flex是一个建立在Flash平台上的富客户端应用开发工具包,Flex 作为富 Internet 应用(RIA)时代的新技术代表,自从 2007 年 Adobe 公司将其开源以来,Flex 就以前所未有的速度在成长。感兴趣的朋友可以过来看看
0
在 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,我们成功地将数据获取逻辑封装起来,并在不同的组件中复用。这种方法不仅解决了数据传递的问题,还提高了代码的可维护性和可测试性。
注意事项:
以上就是使用 React Hooks 在组件间传递数据:构建可复用的数据获取逻辑的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号