When utilizing react + antd framework written in the navigation bar, met some pit, are the first- and second-level menu in the menu click on the case, highlight without any problems, but when then click on the browser back button, but it went wrong .
1. The secondary menu, we can monitor the route through props.history, by assigning a different hash value to the corresponding selectdKeys antd navigation bar can get.
2. The menu may have a problem as well, because the props print out an empty object is to get a menu that, when it listens to the route changes, the browser error, so this time you have to use the withRouter, its use is:
import React, { Component } from 'react' import '../css/movie-app.css' // 导入路由 import { Route, Link, withRouter } from 'react-router-dom' import Home from './home' import Movie from './movie' import About from './about' import { Layout, Menu } from 'antd' const { Header, Content, Footer } = Layout class MovieApp extends Component { constructor (The props) { Super (The props) the console.log (The props) // A print out this object is not empty, and can listen to the route const the hash = props.location.pathname the this .STATE = { SEL: the hash .startsWith ( ' / Movie ' ?) ' / Movie / in_theaters ' : the hash } props.history.listen (route => { const the hash = route.pathname the this .setState ({ SEL: hash.startsWith ( ' / Movie ' ) ? ' / Movie / in_theaters ' : hash }) }) } render() { return ( <Layout className="layout"> <Header> <div className="logo" /> <Menu theme="dark" mode="horizontal" selectedKeys={[this.state.sel]} style={{ display: 'inline-block', width: 300, lineHeight: '64px' }} > <Menu.Item key="/"> <Link to="/">首页</Link> </Menu.Item> <Menu.Item key="/movie/in_theaters"> <Link to="/movie/in_theaters">电影</Link> </Menu.Item> <Menu.Item key="/about"> <Link to="> About </ Link>"/ the About </Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Route path="/" exact component={Home}></Route> <Route path="/movie" component={Movie}></Route> <Route path="/about" component={About}></Route> </Content> <Footer style={{ textAlign: 'center' }}>footer Ant Design ©2018 Created by Ant UED</Footer> </Layout> ) } } export default withRouter(MovieApp)
Note that withRouter must be placed in the routing tag (<Router> </ Router>) inside, or will be error! ! !
Write props to solve the problem can not listen to empty route