首页 > 解决方案 > 使用 React 路由器从 URL 获取 ID(匹配)

问题描述

我正在尝试制作详细信息页面。所以我试图从 url 中获取 id,例如 localhost:3000/65 (65 是 id)。我使用反应路由器。我试图让它首先使用一个简单的控制台日志。

细节.js

const Detail = ({ match }) => {
 
 console.log(match);

  useEffect(() => {
    //console.log(match);
    fetchData(URL, config.KEY).then((response) => {
      console.log(response);
      setDetails(response);
    });
  }, []);

  const [detail, setDetails] = useState([]);

  return <div> detail </div>;
};

export default Detail;

这就是我的路由器的样子


    <Router>
      <div className="App">
        <Header />
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/:id" component={Detail} />
        </Switch>
      </div>
    </Router>

谁能帮我解决这个问题,这样我就可以得到“id”

标签: reactjsreact-router

解决方案


忽略路由器中的拼写错误(parth -> path),访问路由参数的最简单方法是通过 React Router 中的 useParams 挂钩,如下所示:

import { useParams } from "react-router-dom";

const ChildComponent = () => {
 const { id } = useParams();
 return (
   <div>
     <h3>ID: {id}</h3>
   </div>
 );
}

推荐阅读