react中withRouter解决props返回为空

利用 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">
        
"logo" /> <Menu theme="dark" mode="horizontal" selectedKeys={[this.state.sel]} style={{ display: 'inline-block', width: 300, lineHeight: '64px' }} > "/"> "/">首页 "/movie/in_theaters"> "/movie/in_theaters">电影 "/about"> "/about">关于
'0 50px' }}> "/" exact component={Home}> "/movie" component={Movie}> "/about" component={About}>
'center' }}>footer Ant Design ©2018 Created by Ant UED
) } } export default withRouter(MovieApp)

需要注意的是 withRouter 必须要放在路由标签()里边,否则也会报错!!!

这样写就解决了 props 为空不能监听路由的问题

 

转载于:https://www.cnblogs.com/xiaoyaoxingchen/p/10993725.html

你可能感兴趣的:(react中withRouter解决props返回为空)