
在 React 应用中,经常需要在不同的组件和页面之间传递数据。本文旨在帮助开发者掌握在 React 应用中,使用 React Router 在不同组件和页面之间高效传递数据的多种方法。我们将深入探讨如何利用自定义 Hook 函数,结合路由参数,实现数据的安全可靠传递,避免数据丢失或传递失败的问题,并提供详细的代码示例和最佳实践。
方案一:使用自定义 Hook 获取数据
当使用 useLocation 传递数据遇到问题时,一个更可靠的方案是创建一个自定义 Hook 来直接获取数据。 这种方法可以确保数据在目标页面可用,并且避免了由于路由状态管理不当导致的数据丢失。
1. 创建自定义 Hook:
创建一个名为 useCountry.js 的文件,并在其中定义一个 Hook 函数,该函数负责获取国家/地区数据。你可以根据需要传入参数,例如国家/地区代码。
// useCountry.js
import { useState, useEffect } from 'react';
function useCountry(countryCode) {
const [country, setCountry] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchCountry() {
try {
setLoading(true);
const response = await fetch(`https://restcountries.com/v3.1/alpha/${countryCode}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setCountry(data[0]); // Assuming the API returns an array
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
}
if (countryCode) {
fetchCountry();
}
}, [countryCode]);
return { country, loading, error };
}
export default useCountry;2. 在 Details.js 中使用 Hook:
在 Details.js 组件中,导入 useCountry Hook 并使用它来获取数据。 你需要先从路由参数中获取国家代码,然后传递给 useCountry Hook。
// Details.js
import React from 'react';
import Navbar from './components/Navbar';
import { useParams } from 'react-router-dom'; // Import useParams
import useCountry from './useCountry';
function Details() {
const { countryCode } = useParams(); // Get countryCode from URL params
const { country, loading, error } = useCountry(countryCode);
if (loading) {
return Loading country details...
;
}
if (error) {
return Error: {error.message}
;
}
if (!country) {
return Country not found
;
}
return (
<>
Details
{country.name.common}
Population: {country.population}
>
);
}
export default Details;3. 修改 Country.js 中的 Link:
修改 Country.js 组件中的 组件,将国家/地区代码作为 URL 参数传递。
// Country.js
import React from 'react';
import { Link } from 'react-router-dom';
function Country(props) {
const { data, img, cap, reg, alt, name, pop } = props;
const countryCode = data.cca2; // Assuming cca2 is the country code
return (
{/* Use URL parameters */}
@@##@@
{name}
population:
{pop}
region:
{reg}
capital:
{cap}
);
}
export default Country;4. 更新 main.js 中的路由:
修改 main.js 中的路由配置,以支持包含国家/地区代码参数的 /details 路径。
// 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: ,
},
{
path: "/details/:countryCode", // Add the countryCode parameter
element: ,
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
);方案二:使用 Context API (适用于复杂数据共享)
如果需要在多个组件之间共享数据,并且组件层级较深,可以考虑使用 Context API。
1. 创建 Context:
创建一个 Context 文件(例如 CountryContext.js):
// CountryContext.js
import React, { createContext, useState } from 'react';
export const CountryContext = createContext(null);
export const CountryProvider = ({ children }) => {
const [selectedCountry, setSelectedCountry] = useState(null);
return (
{children}
);
};2. 在 App.js 中包裹 Provider:
在 App.js 中,使用 CountryProvider 包裹整个应用:
// App.js
import React from 'react';
import { CountryProvider } from './CountryContext';
// ... 其他导入
function App() {
// ... 其他代码
return (
{/* 应用的其他部分 */}
);
}
export default App;3. 在 Country.js 中更新 Context:
在 Country.js 中,使用 useContext 获取 setSelectedCountry 函数,并在点击链接时更新 Context 中的 selectedCountry:
// Country.js
import React, { useContext } from 'react';
import { Link } from 'react-router-dom';
import { CountryContext } from './CountryContext';
function Country(props) {
const { data, img, cap, reg, alt, name, pop } = props;
const { setSelectedCountry } = useContext(CountryContext);
const handleClick = () => {
setSelectedCountry(data);
};
return (
{/* ... 其他代码 */}
);
}
export default Country;4. 在 Details.js 中使用 Context:
在 Details.js 中,使用 useContext 获取 selectedCountry:
// Details.js
import React, { useContext } from 'react';
import Navbar from './components/Navbar';
import { CountryContext } from './CountryContext';
function Details() {
const { selectedCountry } = useContext(CountryContext);
if (!selectedCountry) {
return No country selected.
;
}
return (
<>
Details
{selectedCountry.name.common}
Population: {selectedCountry.population}
>
);
}
export default Details;总结:
选择哪种方法取决于你的具体需求。
- 自定义 Hook + URL 参数: 适用于需要通过 URL 标识资源的情况,并且数据获取逻辑相对独立。
- Context API: 适用于需要在多个组件之间共享复杂数据,并且组件层级较深的情况。
无论选择哪种方法,都要确保数据传递的正确性和安全性,避免出现数据丢失或错误的情况。 仔细考虑你的应用架构和数据流,选择最适合你的解决方案。










