Javascript React Router V4 获取当前路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50511111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:37:58  来源:igfitidea点击:

React Router V4 Get Current Path

javascriptreactjsreact-router

提问by Filth

How can I get the current path using react router v4?

如何使用 react router v4 获取当前路径?

I have tried the following to no avail:

我尝试了以下方法无济于事:

const currentLocation = this.props.location.pathname;

Error: Cannot read property 'pathname' of undefined

错误: Cannot read property 'pathname' of undefined

Here is my Routes.js file:

这是我的 Routes.js 文件:

import React, {Component} from 'react';
import {  BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import configureStore from './Store';
import LevelOne from './containers/LevelOne';
import LevelTwo from './containers/LevelTwo';
import LevelThree from './containers/LevelThree';
import CreateProfile from './containers/Profile/CreateProfile';
import WhosWatching from './containers/Profile/WhosWatching';
import ProfileNameAvatar from './containers/Profile/ProfileNameAvatar';
import FavouriteGenres from './containers/Profile/FavouriteGenres';
import FourZeroFour from './containers/404';

import Header from './components/Header';

const store = configureStore();

const navItems = [
  {
    title:"For You",
    to: "/for-you"
  },
  {
    title:"Movies",
    to: "/movies"
  },
  {
    title:"Series",
    to: "/series"
  },
  {
    title:"TV Shows",
    to: "/tv-Shows"
  },
  {
    title:"Subscriptions",
    to: "/subscriptions"
  },
  {
    title:"Live TV",
    to: "/live-tv"
  }
]

export default class Routes extends Component {
  state = {
    theme: 'light'
  }

  header = React.createRef();

  setTheme = (theme) => {
    this.setState({
      theme: theme,
    });
  }

  render() {
    const currentLocation = this.props.location.pathname;
    console.log("location", currentLocation);
    return (
      <Provider store={store}>
        <Router ref='router'>
          <div className='app'>
            {/*<Header navItems={navItems} theme={this.state.theme} ref={this.header} />*/}
            <Switch>
              <Route exact path="/" render={(props) => (
                <LevelOne {...props} setTheme={this.setTheme} />
              )}/>
              <Route exact path="/for-you" render={(props) => (
                <LevelTwo {...props} setTheme={this.setTheme} />
              )}/>
              <Route exact path="/for-you/view-all" render={(props) => (
                <LevelThree {...props} setTheme={this.setTheme} innerRef={this.header} />
              )}/>
              <Route exact path="/profile/create-profile" render={(props) => (
                <CreateProfile {...props} />
              )}/>
              <Route exact path="/profile/whos-watching" render={(props) => (
                <WhosWatching {...props} />
              )}/>
              <Route exact path="/profile/profile-name-avatar" render={(props) => (
                <ProfileNameAvatar {...props} />
              )}/>
              <Route exact path="/profile/favourite-genres" render={(props) => (
                <FavouriteGenres {...props} />
              )}/>
              <Route component={FourZeroFour} />
            </Switch>
          </div>
        </Router>
      </Provider>
    );
  }
}

回答by riwu

You will only have access to this.props.locationin a Routecomponent (as the prop is passed to the component from it).

您只能访问this.props.location一个Route组件(因为 prop 是从它传递给组件的)。

You can get the current path with window.location.pathnameoutside of the Router, though it's likely that you are doing something wrong if you are accessing the path here.

您可以在window.location.pathname之外获取当前路径Router,但如果您在此处访问路径,则很可能您做错了什么。

For children of Router, you can access the location by wrapping it around withRouteror pass the prop downwards from a Routecomponent.

对于 的子项Router,您可以通过将其环绕withRouter或从Route组件向下传递 prop来访问该位置。

Redux integrationwill also allow you to access the location from anywhere.

Redux 集成还允许您从任何地方访问该位置。

回答by ingpedrorr

Fast solution
Create a variable on your function:

快速解决方案
在您的函数上创建一个变量:

var currentLocation = window.location.pathname;

and then in the ul > li className={(currentLocation == '/' ? 'active' : '')}

然后在 ul > li className={(currentLocation == '/' ? 'active' : '')}

it worked for mee and is a quick solution.

它对我有用,是一个快速的解决方案。

回答by Steve Bohmbach

this.props.match.pathshould do the trick

this.props.match.path应该做的伎俩

回答by rudresh solanki

you can get the path directly from the documentvariable.

您可以直接从document变量中获取路径。

eg: const path = document.location.pathname

例如: const path = document.location.pathname