React Router 4. 获取活动路由

Mus*_*yan 2 javascript reactjs react-router

我有代码

路由器.js

import React from 'react';
import {render} from "react-dom";
import history from './history';
import {Router, Route} from 'react-router'

import Main from "./main/component";
import Profile from "./profile/component";
import TextStatus from "./textstatus/component";
import ContactList from "./contactlist/component";

render((
  <Router history={history}>
    <Main>
      <Route
        path="/:user_name"
        component={Profile}
        component_id="Profile"
      />
      <Route
        path="/:user_name/status"
        component={TextStatus}
        component_id="TextStatus"
      />
      <Route
        path="/:user_name/contacts"
        component={ContactList}
        component_id="ContactList"
      />
    </Main>
  </Router>

), document.getElementById("main"));
Run Code Online (Sandbox Code Playgroud)

历史.js

import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();
export default history;
Run Code Online (Sandbox Code Playgroud)

main/component.js //主布局

import React from 'react';
class Main extends React.Component {
   render() {
      return (this.props.children)
   }
}
Run Code Online (Sandbox Code Playgroud)

如何在 Main 组件中获取当前路由 (component_id)?

在反应路由器 1.0.3 我这样做了: this.props.children.props.route.component_id

感谢您的关注!

Dan*_*ane 9

React v16.8+ 和 React Router v5+ 的更新

使用useLocation钩子。

import { useLocation } from 'react-router-dom';

const Main = ({ children }) => {
  const location = useLocation();
  
  console.log(location.pathname); // outputs currently active route
  return children;
};

export default Main;
Run Code Online (Sandbox Code Playgroud)

用 包裹您的组件,withRouter然后您可以使用this.props.location.pathname.

例如:

import React from 'react';
class Main extends React.Component {
   render() {
      console.log(this.props.location.pathname); // outputs currently active route
      return (this.props.children)
   }
}
export default withRouter(Main);
Run Code Online (Sandbox Code Playgroud)