reactjs - 使用 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”
解决方案
忽略路由器中的拼写错误(parth -> path),访问路由参数的最简单方法是通过 React Router 中的 useParams 挂钩,如下所示:
import { useParams } from "react-router-dom";
const ChildComponent = () => {
const { id } = useParams();
return (
<div>
<h3>ID: {id}</h3>
</div>
);
}
推荐阅读
- r - 将专有的持续时间格式转换为毫秒
- css - 日文从上到下内容的 CSS3 {text-align: start}
- java - 在哪里放置泛型类型
- javascript - 重建对象数组后重新索引对象数组中的元素
- azure-devops - Azure Devops Pipeline - 使用 Microsoft Visual Studio 安装程序项目
- python - 为每个游戏列出正确的获胜者 Python
- python - 如何使用 lxml 从 xpath 获取所有文本
- google-cloud-platform - 如何在 Google Cloud Platform 中跨服务 (API) 和项目查找、列出或搜索资源?
- reactjs - 如何防止 componentWillReceiveProps 为这里的每个 setState 渲染?
- automata - 确定性下推自动机与非确定性下推自动机