zoukankan      html  css  js  c++  java
  • 笔记react router 4(五)

      或许,你觉得我麻烦,明明一篇文章可以搞定的内容,非要写几篇。是不是正在吐槽我?没关系,我的目的达到了。手动傲娇( ̄∇ ̄)

    然后,我们就要来聊一聊withRouter了。

    我们都知道,当我在访问路由配置文件中的组件,通常我们称之为路由组件时,可以从他的props中访问到路由对象。如,location。但是,没有声明在路由中的组件,通常我们称之为非路由组件,比如路由组件中我们使用到的外部组件时,我们需要用到路由对象该怎么办呢?

    在3.X中,我们要在非路由组件中使用history对象,需要手动引入history,就像这样,

    import createHistory from 'history/createBrowserHistory'
    const history = createHistory()

    或者,我们在路由组件中将获取到的路由对象手动传递给外部组件。

    <Parent>
        <Child routeProps = {this.props.location} />
    </Parent>

    再或者,我们可以使用H5的history API。

    window.location

    但是4.X中我们可以不用那么麻烦了,直接一个withRouter包裹你的外部组件,即可通过props访问到location, router及history等对象。

    就像这样,

    import React from 'react'
    import PropTypes from 'prop-types'
    import { withRouter } from 'react-router'
    
    class ShowTheLocation extends React.Component {
      static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      }
    
      render() {
        const { match, location, history } = this.props
    
        return (
          <div>You are now at {location.pathname}</div>
        )
      }
    }
    
    const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
    来自:https://reacttraining.com/react-router/web/api/withRouter

      接着再来看, component.WrappedComponent

    // MyComponent.js
    export default withRouter(MyComponent)
    
    // MyComponent.test.js
    import MyComponent from './MyComponent'
    render(<MyComponent.WrappedComponent location={{...}} ... />)

    它用于创建一个包装组件上,通常用于测试。

      wrappedComponnetRef这个函数的作用是refs获取组件实例。

    class Container extends React.Component {
      componentDidMount() {
        this.component.doSomething()
      }
    
      render() {
        return (
          <MyComponent wrappedComponentRef={c => this.component = c}/>
        )
      }
    }
  • 相关阅读:
    0909我眼中的编译原理
    你要的所有数据源都在这里了!
    JAVA多线程和并发基础
    写的代码小有成就+今日总结--购买产品---20200508
    mysql数据库时区问题
    【Spring】——声明式事务配置详解
    SpringBoot整合阿里云OSS文件上传、下载、查看、删除
    一文看懂:网址,URL,域名,IP地址,DNS,域名解析
    git快速入门
    批处理框架spring batch基础知识介绍
  • 原文地址:https://www.cnblogs.com/zyl-Tara/p/9686049.html
Copyright © 2011-2022 走看看