如何在React的每个路由路径中传递查询参数?

时间:2019-06-12 11:12:13

标签: reactjs react-router

我正在尝试使用类似http://localhost:3000/login?Id=1这样的查询参数来实现React Router,即使将路径设置为http://localhost:3000/,然后重定向,我也只能为我的登录路由实现它,但是,我想在整个应用程序中实施。如果我在其他路线上实施,则它与nomatch路线相匹配。这就是我的index.js的样子,有人可以指导我如何实现包括查询参数在内的所有路由路径吗?。

ReactDOM.render(
      <BrowserRouter>
        <Switch>
          <Route
            exact
            path={`/`}
            render={() => {
              if (!store.getState().login.isAvailable) {
                return <Redirect to={`/login?Id=${Id}`} />
              } else {
                return <Dashboard />
              }
            }}
          />
          <Route exact path={`/login`} component={Login} />
          <Route exact path={`/signup`} component={SignUp} />
          {Routes.map((prop, key) => (
            <Route path={prop.path} key={key} component={prop.component} />
          ))}
          <Route component={NoMatch} />
        </Switch>
      </BrowserRouter>,
  document.getElementById('root')
)

1 个答案:

答案 0 :(得分:0)

有两种方法可以完成您想要的。 最基本的方法是在每个路由的每个“页面”或根组件上,处理查询参数的解析。

作为component组件的Route的任何组件都将传递道具location。查询参数位于location.search中,需要对其进行解析。如果您只担心现代浏览器,则可以使用URLSearchParams,也可以使用query-string之类的库,当然,也可以自己解析它们。

您可以在react-router docs中阅读更多内容。

第二种方法确实没有什么不同,但是您可以拥有一个HOC,该HOC包裹处理查询参数解析的每个“页面”,并将它们作为列表或其他内容传递给有问题的“页面”组件。

下面是使用URLSearchParams的基本方法的示例:

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

// this is your "page" component, we are using the location prop
function ParamsPage({ location }) {
  // you can use whatever you want to parse the params
  let params = new URLSearchParams(location.search);

  return (
    <div>
      <div>{params.get("name")}</div>
      // this link goes to this same page, but passes a query param
      <a href="/?name=MyName">Link that has params</a>
    </div>
  );
}

// this would be equivalent to your index.js page
function ParamsExample() {
  return (
    <Router>
      <Route component={ParamsPage} />
    </Router>
  );
}

export default ParamsExample;

编辑:为了明确起见,您无需在index.js页面上进行任何操作即可完成此工作,您拥有的简单Route s应该可以正常工作。

相关问题