将当前路由与React Router匹配

时间:2019-05-19 13:08:31

标签: reactjs

此应用程序包装在路由器中,要使用路径名查找当前网址,这是我尝试中唯一无法解决的问题,

<Router history={history}>
  <SegmentMenu {...this.props} {...this.state} />
  <Route path="/" exact render={() => <Home {...this.state} pagename='Home' />} />
  <Route path="/auth" render={() => <Auth {...this.state} />} />
  <Route path="/terms" component={Terms} />
  <Footer />
</Router>

在每个componentWillMount上运行此命令以找到url并向菜单中添加一些逻辑:

 componentWillMount = (props) => {
    if (window.location.pathname === '/') {
      this.setState({ pagename: 'Anytime, anywhere.', home: true });
    }
    else if (window.location.pathname === '/dashboard') {
      this.setState({ pagename: 'Dashboard', dashboard: true });
    }
    else if (window.location.pathname === '/privacy') {
      this.setState({ pagename: 'Privacy', privacy: true });
    }
    else if (window.location.pathname === '/auth') {
      this.setState({ pagename: 'Account', auth: true });
    }

  ...

这变得越来越长,我该如何改善呢? pagename是屏幕的标题,下一个变量是onFocus

1 个答案:

答案 0 :(得分:1)

您将需要将路由配置存储在一个数组中,以便以后用于检查当前路由是否与路径匹配。 react-router提供了一个matchPath函数,该函数可用于检查当前props.location.pathname是否与路由对象匹配。这样,您可以创建一个HOC函数,该函数会将当前活动的路线对象作为道具添加到您的组件中。

请参阅:https://codesandbox.io/s/0ikhi

示例

routes.js

import DebugComponent from "./DebugComponent";

const routes = [
  {
    title: "Home",
    path: "/",
    exact: true,
    component: DebugComponent
  },
  {
    title: "About",
    path: "/about",
    exact: true,
    component: DebugComponent
  }
];

export default routes;

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import routes from "./routes";

import "./styles.css";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Switch>
          {routes.map(route => (
            <Route {...route} key={route.title} />
          ))}
        </Switch>
      </BrowserRouter>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

DebugComponent.js

import React from "react";
import withActiveRoute from "./withActiveRoute";

const DebugComponent = props => (
  // You have access to `props.activeRoute.title`
  <pre>{JSON.stringify(props.activeRoute, null, 2)}</pre>
);

export default withActiveRoute(DebugComponent);

withActiveRoute.js

import React from "react";
import { matchPath, withRouter } from "react-router";
import routes from "./routes";

const withActiveRoute = Component => {
  const ActiveRoute = props => {
    const activeRoute = routes.find(route => {
      return matchPath(props.location.pathname, route);
    });

    return <Component {...props} activeRoute={activeRoute} />;
  };

  return withRouter(ActiveRoute);
};

export default withActiveRoute;