无法从带id的路由获取Params参数问题求助
this.props.match.params.id Returning Undefined Hey Nicolas, let's work through why you're getting undefined when trying to access the route parameter in your Show component. Here are the most common fixes to check:
Check if your Show component is a functional component
If Show is a functional component (not a class component),this.propswon't exist at all—so accessingthis.props.matchwill always return undefined. Instead, use theuseParamshook fromreact-router-domto grab the ID:import { useParams } from 'react-router-dom'; const Show = () => { const { id } = useParams(); console.log(id); // This should log the correct ID now return <div>Showing item: {id}</div>; }; export default Show;For class components: Ensure router props are being passed
If Show is a class component, sometimes wrapping it with other higher-order components (likeReact.memoor custom HOCs) can block the router props from reaching it. Fix this by wrapping Show withwithRouter:import React from 'react'; import { withRouter } from 'react-router-dom'; class Show extends React.Component { render() { const { id } = this.props.match.params; console.log(id); // Should now be defined return <div>Showing item: {id}</div>; } } // Wrap the component with withRouter to inject router props export default withRouter(Show);Double-check your navigation method
You mentioned your Home component has an async function—make sure you're using React Router's built-in navigation to get to the Show route, not manually changing the URL. For example:// In a class-based Home component async handleAsyncAction() { await yourAsyncTask(); // Use history.push to navigate (router props include history) this.props.history.push(`/show/${someId}`); } // In a functional Home component import { useHistory } from 'react-router-dom'; const Home = () => { const history = useHistory(); const handleAsync = async () => { await yourAsyncTask(); history.push(`/show/${someId}`); }; return <button onClick={handleAsync}>Go to Show</button>; };Confirm your route order is correct
Good news—your current route order (/show/:idbefore/) is right! TheSwitchcomponent matches the first route it finds, so the Home route won't override your Show route. Just make sure you're visiting a URL likehttp://your-app.com/show/123(not something missing the ID segment).
内容的提问来源于stack exchange,提问作者Nicolas Albarracin

