gpt4 book ai didi

javascript - React Router V4 获取当前路径

转载 作者:数据小太阳 更新时间:2023-10-29 05:40:38 33 4
gpt4 key购买 nike

如何使用 React Router v4 获取当前路径?

我试过以下方法都没有用:

const currentLocation = this.props.location.pathname;

错误:无法读取未定义的属性“路径名”

这是我的 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>
);
}
}

最佳答案

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

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

对于 Router 的 child ,您可以通过将其包裹在 withRouter 周围来访问该位置或者从 Route 组件向下传递 prop。

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

关于javascript - React Router V4 获取当前路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50511111/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com