react-router - React Router如何使用查询参数和多个查询参数将路径重定向到同一组件?
问题描述
我有一个名为TableComponent
. 我想将路径重定向tables/:table
到tables/:table?tab=tab1
并且所有不同的选项卡都使用相同的TableComponent
. 例如:
tables/:table?tab=tab1
->TableComponent
tables/:table?tab=tab2
->TableComponent
tables/:table?tab=tab3
->TableComponent
我有下面的代码,但它不起作用:
<Redirect
exact
from="/tables/:table"
to={{
pathname: "/tables/:table",
search: "?tab=tab1"
}}
/>
<Route
path="/tables/:table" <- how can I make this route ignore the query params?
component={TableComponent}
/>
或者我应该在里面做重定向TableComponent
?
解决方案
编辑:
在 Table 组件上方添加一个父组件,并使用 React Router 的 useHistory 检查 URL 中是否有查询参数。如果没有,请使用 useHistory 钩子并执行 history.push(tables/:table?tab=tab1)。
原始答案:
我认为您不需要重定向。使用路线将您带到 TableComponent。
<Route
path="/tables/:table"
component={TableComponent}
/>
当用户单击应该指向某个选项卡的链接时,将查询参数添加到 URL,如下所示:
<Link to={`tables/${table}?tab=${tab}`}
URL 可以是类似的tables/august-finances?tab=1
东西。
在表格组件中,使用useHistory
钩子查看是否有搜索参数以及它是什么。这是钩子的内置道具。URL 中之后的任何内容?
都可以从历史记录中查看。
前任。
import { useState, useEffect } from 'react;
import { useHistory } from 'react-router;
const TableComponent = () => {
// create state for the tab and set it to null
const [tab, setTab] = useState(null);
let history = useHistory();
useEffect(() => {
// this will be `tab=tab1`
const queryString = history.search;
//isolate the tab by splitting the string by the = character
// it will create array ["tab","tab1"], get the "tab1"
const currentTab = queryString.split("=")[1];
setTab(currentTab);
},[history]);
return(
// if !tab, return nothing
// if tab does have a value, use a conditional expression to return which tab of the table should be shown first
)
}
推荐阅读
- python - 使用 tkinter,我如何告诉我的脚本使用 IDLE 编辑器?
- autohotkey - 使 Autohotkey 单击 chrome 中的特定按钮
- python - 加快重叠时间间隔的检测
- css - 如何在 MessagePage 内将按钮图标更改回正常大小?
- javascript - 一旦使用javascript单击第一个对话框的按钮,我想显示另一个具有相同样式的对话框
- docker - Docker-compose - 高效开发
- r - lapply 和 sapply 函数可以用在具有不同 R 基函数的矩阵或数据帧上吗?
- linux - 是否可以在外部数据文件操作命令中使用 gnuplot 变量?
- sql - SQL 日期逻辑 - 查找之前的*非标准*季度
- postgresql - Azure 数据工厂通过 SSH 连接到 AWS RDS PostgresSQL