首页 > 解决方案 > React Router如何使用查询参数和多个查询参数将路径重定向到同一组件?

问题描述

我有一个名为TableComponent. 我想将路径重定向tables/:tabletables/: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

标签: react-router

解决方案


编辑:

在 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
)
} 

推荐阅读