reactjs - 反应:this.props.location.pathname 未定义
问题描述
告诉我如何访问pathname
?参数this.props
为空this.props.location
且未定义。
不用自己设置,如何自动获取这个参数?
找到的大多数解决方案都需要我自己(手动)设置这个参数,这不是很方便并且使代码复杂化。
ReactDOM.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
document.getElementById('root')
);
function App() {
return (
<Container>
<Row><GeneralMenu /></Row>
<Row>
<Switch>
<Route exact path="/block1">
<PageStrategy />
</Route>
<Route exact path="/block2">
<PageStrategy />
</Route>
</Switch>
</Row>
</Container>
);
}
class GeneralMenu extends Component {
render() {
// {location} = this.props.location.pathname;
return (
<Navbar>
<Nav activeKey = {this.props.location.pathname}>
<Nav.Link href = "/block1">Block1</Nav.Link>
<Nav.Link href = "/block2">Block2</Nav.Link>
</Nav>
</Navbar>
);
}
}
解决方案
您应该以这种方式使用withRouter()
HOC GeneralMenu
:
export default withRouter(GeneralMenu);
然后使用导出的元素。
你也可以做这样的事情,而不导出元素:
const WithRouterGeneralMenu = withRouter(GeneralMenu);
推荐阅读
- python - cv2轮廓区域返回值
- input - 如何将时间类型的输入与 blazor 绑定
- c++ - C++ 在数据更改时更新 mfc ui
- android - 我应该如何处理错误 RecyclerView: No adapter attach; 跳过布局
- reactjs - 为什么反应只有视图层?
- html - 如何在定义的位置换行?
- django - 如何将字符串转换为 CharField
- java - 如何对字符串数组列表、java 8 或 java 11 进行分组
- php - 用户注册后重定向到登录页面。拉拉维尔 5.5
- dialogflow-es - 如何在 Google Assistant 上的帐户链接中替换默认响应