首页 > 解决方案 > 使用 React、React Router 和 Firebase(useParams 或 useRouteMatch)设置 URL 参数?

问题描述

我正在实施的内容:

我正在为一个项目使用 React(使用 Hooks)、React Router 和 Firebase,并且我想使用 documentId 作为单击文档时的 url。网址如下所示:https ://website.com/view-companies/sdf920k1

应用程序.js

<Route path="/view-companies/:documentId" component={ViewCompany} />

我的问题:

我已经在我的 App.js 中使用 :documentId 作为参数设置了我的 Route 路径,但我不确定要使用哪个钩子(useParamsuseRouteMatch),以及我是否在设置中遗漏了一些东西。

当我查询 Cloud Firestore 并返回 7 个文档时,我想选择一个文档,并且在 url 中使用了 documentId。我尝试在 Github 上为 Firebase 寻找此设置的示例,但没有任何运气。

标签: reactjsfirebasegoogle-cloud-firestorereact-routerreact-router-dom

解决方案


当您单击文档时,您可以使用历史记录更新 url,例如

const Component = () => {
   const history = useHistory();

   const handleClick = (documentId) => {
      history.push(`/view-companies/${documentId}`);
   }

   ...
}

PS 如果您使用 v6 的 react-router,您将使用 useNavigate 而不是 useHistory

现在在您根据可用于useParams获取参数的路线呈现的组件中

const ViewCompany = () => {
   const { documentId } = useParams();
   // do what want with documentId 

   ...
}

推荐阅读