【问题标题】:Setting URL Parameters with React, React Router, and Firebase (useParams or useRouteMatch)?使用 React、React Router 和 Firebase(useParams 或 useRouteMatch)设置 URL 参数?
【发布时间】:2020-09-13 10:27:26
【问题描述】:

我正在实施的内容:

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

App.js

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

我的问题:

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

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

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore react-router react-router-dom


    【解决方案1】:

    当你点击文档时,你可以像这样更新 url 的历史记录

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

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

    现在在您根据路由渲染的组件中,您可以使用useParams 来获取参数

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

    【讨论】:

    • 感谢您的支持。帮助!我正在使用npm包react-router-dom,但最新版本是5.1.2。我应该使用 react-router 吗?
    • 不,react-router-dom 是 v5 的细沙,您可以按照我在帖子中的建议使用 useHistory
    猜你喜欢
    • 2021-05-06
    • 2022-11-11
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多