react 如何匹配 query 的路由

我要做一个搜索的功能,路由是这样的

/home?keywords=xxx

我的路由代码是

<Router>
  <ScrollToTop />
  <Header />
  <div style={{paddingTop: '57px'}}>
    <Switch>
      <Redirect exact from="/" to="/home" />
      <Route path="/home" component={Home}/>
      <Route path="/detail/:id" exact component={Detail}/>
      <Route path="/login" exact component={Login}/>
      <Route path="/register" exact component={Register}/>
      <Route path="/404" exact component={NoMatch}/>
      <Redirect from="*" to="/404"/>
    </Switch>
  </div>
</Router>

但是 /home 匹配不了 /home?keywords=xxx 这个路由,所以每次搜索都跳到了404界面 所以我想问问怎么匹配这个路由

阅读 5.4k
2 个回答

跳转时/home?keywords=xxx

在home页面获取参数

const params = new URLSearchParams(this.props.location.search)
console.log(params.get("keywords"))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题