利用 react + antd 框架書寫導航欄時,遇到了幾個坑,分別是一級菜單和二級菜單在點擊的情況下,高亮沒有任何問題,但是再點擊瀏覽器返回按鈕時,卻就亂套了。
1. 二級菜單中,我們可以通過 props.history 來監聽 route ,通過不同的 hash 值賦值給 antd 導航欄相應的 selectdKeys 就能搞定。
2. 以及菜單可就有點問題了,因為一級菜單所拿到的 props 打印出來就是一個空對象,當給它監聽路由變化時,瀏覽器就會報錯,所以這個時候就得用到 withRouter 了,其使用方法為:
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(props) { super(props) console.log(props) // 此時這里打印出來就不是空對象了,就可以對路由進行監聽 const hash = props.location.pathname this.state = { sel: hash.startsWith('/movie') ? '/movie/in_theaters' : hash } props.history.listen(route => { const hash = route.pathname 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> </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)
需要注意的是 withRouter 必須要放在路由標簽(<Router></Router>)里邊,否則也會報錯!!!
這樣寫就解決了 props 為空不能監聽路由的問題