当前位置 : 主页 > 网页制作 > React >

react中withRouter解决props返回为空

来源:互联网 收集:自由互联 发布时间:2021-06-15
利用 react + antd 框架书写导航栏时,遇到了几个坑,分别是一级菜单和二级菜单在点击的情况下,高亮没有任何问题,但是再点击浏览器返回按钮时,却就乱套了。 1. 二级菜单中,我们

利用 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 为空不能监听路由的问题

网友评论