You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法从带id的路由获取Params参数问题求助

Troubleshooting 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.props won't exist at all—so accessing this.props.match will always return undefined. Instead, use the useParams hook from react-router-dom to 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 (like React.memo or custom HOCs) can block the router props from reaching it. Fix this by wrapping Show with withRouter:

    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/:id before / ) is right! The Switch component matches the first route it finds, so the Home route won't override your Show route. Just make sure you're visiting a URL like http://your-app.com/show/123 (not something missing the ID segment).

内容的提问来源于stack exchange,提问作者Nicolas Albarracin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:31:17