reactjs - 使用 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 路径,但我不确定要使用哪个钩子(useParams或useRouteMatch),以及我是否在设置中遗漏了一些东西。
当我查询 Cloud Firestore 并返回 7 个文档时,我想选择一个文档,并且在 url 中使用了 documentId。我尝试在 Github 上为 Firebase 寻找此设置的示例,但没有任何运气。
解决方案
当您单击文档时,您可以使用历史记录更新 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
...
}
推荐阅读
- wordpress - 在 WooCommerce 订单页面上显示图像
- android - Glide 不加载 ModelLoader 工厂
- javascript - 尝试通过 Javascript 验证表单,但代码无法正常工作
- django - 如何使用 django 和 jquery 为所有帖子创建一个赞按钮?
- c# - 即使屏幕不活动,如何在睡眠模式下运行循环方法?
- python - 如何在特定列中找到最大值并在我的数据框的另一列中返回相应的值?
- node.js - Express 中间件未按正确顺序执行
- processing - 处理 - 如何加载 .txt 文件并绘制 2d 形状?
- ios - ios NSLayoutConstraint activate 不会立即在 UICollectionViewCell 内应用
- c++ - 快速傅立叶变换:即使标头和 .cpp 文件匹配,也使用模板派生类“未定义引用”错误