首页 > 解决方案 > 将路由器与其他查询参数反应相同的路径

问题描述

如果 queryParam 更改但路径保持不变,react-router 是否可以更改路由?我定义了两条路线:

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={List} />
    <Route path="/=" component={Content} />
  </Switch>
</BrowserRouter>

我的列表视图基本上显示了一个项目列表。当有人点击该项目时,网址应更改为/?content=content-id.

最终的申请应该有以下路线:

"/" => render List View
"?content=content-id" => render Content View

谢谢你的帮助

标签: reactjsreact-routerreact-router-dom

解决方案


首先,您可以执行以下操作

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={List} />
    <Route path="/:id=" component={Content} />
  </Switch>
</BrowserRouter>

在 Contect.js 中:

let { id } = useParams();//if it's func component

或者

    this.props.history.push({
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>
})

在第二种方式中,您可以进行查询并使用它发送状态。


推荐阅读