反应。无法在嵌套组件中使用 useParams() 获取 URL 参数

React. Cannot get URL params with useParams() in nested component

我有一个简单的演示应用程序,您可以在其中单独查看报价 (QuoteDetail) 并查看报价下的评论。我在两个组件中都需要 url 参数,但我只能在父组件中获取它们。

App.tsx:

<Switch>
  // ...
  <Route path="/quotes" exact>
    <AllQuotes />
  </Route>
  <Route path="/quotes/:quoteId">
    <QuoteDetail />
  </Route>
  // ...
</Switch>

QuoteDetail.tsx:

export interface QuoteDetailParams {
  quoteId: string;
}

const QuoteDetail: React.FC<QuoteDetailProps> = (props) => {
  const match = useRouteMatch();
  const { quoteId } = useParams<QuoteDetailParams>();
  // ...

  console.log(quoteId); // <-- THIS ONE WORKS      
  // ...

  return (
    <React.Fragment>
      {quote}
      <Route path={match.path} exact>
        <div className="centered">
          <Link className="btn--flat" to={`${match.url}/comments`}>
            Show Comments
          </Link>
        </div>
      </Route>
      <Route path={`${match.url}/comments`} exact>
        <div className="centered">
          <Link className="btn--flat" to={`/quotes/${quoteId}`}>
            Hide Comments
          </Link>
        </div>
        <Comments />
      </Route>
    </React.Fragment>
  );
};

如您所见,当我单击按钮加载评论时,url 从 /quotes/1/ 变为 /quotes/1/comments,这也应该加载 Comments 组件.但是,在 Comments.tsx 中,我无法访问 url 参数。

Comments.tsx:

const Comments = () => {
  const params = useParams<QuoteDetailParams>();
  const { quoteId } = params;
  // ...

  console.log(params); <-- THIS ONE RETURNS undefined

  // ...

  return (
    <section className={classes.comments}>
      <h2>User Comments</h2>
      {comments}
    </section>
  );
};

我不知道我做错了什么。当然,我也可以使用 component prop 传递参数,但在我的情况下这不是我想要的。感谢帮助。

我正在使用 react-router-dom@5.3.0

match

  • match.url 是 URL 的一部分,对于构建嵌套的 <Link>s 很有用。
  • match.path 是用于打补丁的路径模式,对于构建嵌套的 <Route>s 很有用。

您的 QuoteDetail 组件正在使用 match.url 构建嵌套路由,而它应该使用 match.path

<Route path={`${match.url}/comments`} exact> // <-- incorrect route path
  ...
</Route>

应该是:

<Route path={`${match.path}/comments`} exact>
  ...
</Route>