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

如何将item.id值替换到axios.get接口路径中的:Id占位符位置

你需要先确保路由规则配置了参数占位符,再在detail页面通过React Router提供的useParams钩子获取路径中的ID值,具体操作如下:

步骤1:配置路由规则

首先在你的路由配置文件(通常是App.js)中,确保detail页的路由路径携带id参数占位符:

  • React Router v5 配置示例:
<Route path="/detail/:id" component={Detail} />
  • React Router v6 配置示例:
<Route path="/detail/:id" element={<Detail />} />

步骤2:修改detail.js代码

在detail.js文件中导入useParams钩子,提取路径中的id值替换axios请求的占位符,同时给useEffect添加id作为依赖项,避免参数变化时不重新请求数据。
修改后的完整代码如下:

import { useParams } from 'react-router-dom'; // 顶部导入钩子

// 组件内部代码
useEffect(() => {
  const { id } = useParams(); // 提取路径中的id参数
  axios
    .get(`http://localhost:5000/api/kam/${id}`) // 用模板字符串拼接id
    .then((response) => {
      console.log(response);
      setData(response.data.kamData);
    })
    .catch((error) => {
      console.log(error);
    });
}, [id]); // 把id加入依赖数组,id变化时自动重新请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:57:02