React路由中如何将:url_code参数传递至File组件?
:url_code to the File Component Hey there! Let's walk through how to grab that :url_code parameter from your route and use it in your File component. Based on your current React Router setup (using <Switch> and component prop in routes), you're likely using React Router v5—here are two straightforward ways to do this:
Method 1: Use the Route Props
When you use component={File} in your Route, React Router automatically passes three route-specific props to the component: match, location, and history. You can access the url_code parameter from match.params:
import React, { Fragment } from 'react'; import { Item } from './../components/Item.component'; export const File = (props) => { // Destructure url_code from match.params const { url_code } = props.match.params; return ( <Fragment> <h3>Current URL Code: {url_code}</h3> <hr /> <Item /> </Fragment> ); };
Method 2: Use the useParams Hook (React Router v5.1+)
If your React Router version is 5.1 or later, you can use the useParams hook for a cleaner, more concise approach. This works great for function components like your File component:
First, make sure to import useParams from react-router-dom:
import React, { Fragment } from 'react'; import { useParams } from 'react-router-dom'; // Don't forget this import! import { Item } from './../components/Item.component'; export const File = () => { // Directly destructure the url_code parameter const { url_code } = useParams(); return ( <Fragment> <h3>Current URL Code: {url_code}</h3> <hr /> <Item /> </Fragment> ); };
Quick Note for React Router v6 (Future Upgrade)
If you ever upgrade to React Router v6, the route setup changes a bit (using <Routes> instead of <Switch> and element prop instead of component), but grabbing the parameter is still done with useParams:
// Example v6 Route Config <Routes> <Route path="/:url_code" element={<File />} /> </Routes>
The useParams hook usage in the File component remains exactly the same as the v5 example above.
内容的提问来源于stack exchange,提问作者MegaRoks

