React Router V4如何获取当前路径?尝试方法报错求助
解决React Router V4中
Cannot read property 'pathname' of undefined的问题 我来帮你梳理下这个错误的原因,以及对应的解决办法:
问题根源
你的Routes组件作为应用的根组件之一,并没有被<Route>组件包裹,所以React Router不会自动给它注入location、history这类路由相关的props。这就导致你尝试访问this.props.location.pathname时,this.props.location是undefined,从而抛出错误。
解决方案一:使用withRouter高阶组件(适配你的类组件写法)
这是最直接的方案,withRouter可以把路由相关的props注入到任何组件中,不管它是否被<Route>渲染。
修改你的Routes.js代码:
- 首先从
react-router-dom导入withRouter:
import { BrowserRouter as Router, Route, Switch, withRouter } from 'react-router-dom';
- 最后导出组件时用
withRouter包裹:
export default withRouter(Routes);
或者你也可以直接在类定义时包裹:
export default withRouter(class Routes extends Component { // 你的原有组件代码完全不用修改 });
做完这两步后,你的Routes组件就能正常获取到this.props.location,this.props.location.pathname也能正确返回当前路径了。
解决方案二:改为函数组件使用useLocation钩子
如果你愿意把类组件改成函数组件,也可以用React Router的useLocation钩子直接获取当前位置:
- 导入需要的钩子:
import React, { useState } from 'react'; import { BrowserRouter as Router, Route, Switch, useLocation } from 'react-router-dom';
- 重构
Routes为函数组件:
export default function Routes() { const [theme, setTheme] = useState('light'); const location = useLocation(); console.log("location", location.pathname); const setThemeHandler = (newTheme) => { setTheme(newTheme); }; return ( <Provider store={store}> <Router> <div className='app'> <Switch> <Route exact path="/" render={(props) => ( <LevelOne {...props} setTheme={setThemeHandler} /> )}/> {/* 其他Route定义保持不变 */} </Switch> </div> </Router> </Provider> ); }
小提示
另外注意一下,你代码里的<Router ref='router'>使用了字符串ref,这是React不推荐的旧写法,建议换成React.createRef():
// 在组件内部定义 routerRef = React.createRef(); // 然后在Router上使用 <Router ref={this.routerRef} />
内容的提问来源于stack exchange,提问作者Filth
相关产品推荐
相关产品推荐

