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

React Router中useParams获取id为undefined的问题排查

问题解决:Sale组件中useParams获取id为undefined的问题

问题核心是BookDetails组件无法获取有效的id值,导致跳转Sale时传递的id是undefined,最终Sale组件通过useParams()拿不到id。具体原因:

  • BookDetails的路由路径books/:booktitle未包含id参数,useParams()无法获取id;
  • Dashboard跳转到BookDetails时仅传递了booktitle,未传入book.id,BookDetails没有id的有效来源。

方案1:通过路由参数传递id(推荐)

这种方式符合RESTful路由设计,直接通过URL传递资源标识:

  1. 更新路由配置,给BookDetails路由添加id参数:
// App.js
<Route path="books" element={<Dashboard />} />
<Route path="books/:booktitle/:id" element={<BookDetails />} />
<Route path="books/:booktitle/sale/:id" element={<SaleStore />} />
  1. 修改Dashboard的跳转链接,同时传递booktitle和id:
// Dashboard.js
{books.map((book) => (
  <div className="col" key={book.id}>
    <div className="card h-100" >
      <div className="card-img-top pb-5 mb-5"></div>
      <div className="card-body">
        <Link to={`/books/${encodeURIComponent(book.title)}/${book.id}`}>
          <button type="submit" className="btn custome-btn purple-active-ghost w-100">
            {book.title}
          </button>
        </Link>
        {/* 其余代码 */}
      </div>
    </div>
  </div>
))}
  1. BookDetails中获取id并跳转Sale:
// BookDetails.js
import { useParams } from 'react-router-dom';

const { booktitle, id } = useParams();
console.log("book Title:", booktitle);
console.log("book Id:", id); // 现在能获取到有效id

<Link to={`/books/${encodeURIComponent(booktitle)}/sale/${id}`}>
  <button type="submit" className="btn custome-btn purple-active-ghost w-100">
    go to sale
  </button>
</Link>

方案2:通过React Router State传递id(无需修改路由)

如果不想改动现有路由结构,可以通过Link的state属性隐式传递id:

  1. 修改Dashboard的跳转链接,添加state参数:
// Dashboard.js
{books.map((book) => (
  <div className="col" key={book.id}>
    <div className="card h-100" >
      <div className="card-img-top pb-5 mb-5"></div>
      <div className="card-body">
        <Link 
          to={{
            pathname: `/books/${encodeURIComponent(book.title)}`,
            state: { id: book.id }
          }}
        >
          <button type="submit" className="btn custome-btn purple-active-ghost w-100">
            {book.title}
          </button>
        </Link>
        {/* 其余代码 */}
      </div>
    </div>
  </div>
))}
  1. BookDetails中从state获取id并跳转:
// BookDetails.js
import { useParams, useLocation } from 'react-router-dom';

const { booktitle } = useParams();
const { state } = useLocation();
const id = state?.id; // 可选链避免state为undefined时报错

console.log("book Title:", booktitle);
console.log("book Id:", id); // 现在能获取到有效id

<Link to={`/books/${encodeURIComponent(booktitle)}/sale/${id}`}>
  <button type="submit" className="btn custome-btn purple-active-ghost w-100">
    go to sale
  </button>
</Link>

完成上述修改后,Sale组件就能通过useParams()正常获取到id值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 12:22:41