zoukankan      html  css  js  c++  java
  • 高阶组件——withRouter的原理和用法

    作用:

    高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.

    把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上

    1. 默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用编程式导航的写法,执行this.props.history.push('/ ')跳转到对应路由的页面
    然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props
    2. 高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.此时这个组件就具备了路由的属性
     
    使用withRouter:
    比如app.js这个组件,一般是首页,不是通过路由跳转过来的,而是直接从浏览器中输入地址打开的,如果不使用withRouter此组件的this.props为空,没法执行props中的history、location、match等方法
     1 import { Switch, Route, Redirect, withRouter } from "react-router-dom";
     2 
     3 import Home from "./components/Home.jsx";
     4 import User from "./components/User.jsx";
     5 
     6 class App extends React.Component {
     7   constructor(props) {
     8     super(props)
     9     console.log(props)     // 此时props里就具备了路由对象
          props.history.listen((e) => {           // 只要是具备路由功能的组件都可以使用这个方法,参数接收一个回调函数
               console.log(e, '路由参数的变化')
             })
    10   }
    11   render() {
    12     return (
    13       <div>
    14         <Switch>
    15           <Redirect from="/" to="/home" exact />
    16           <Route exact path="/home" component={Home}></Route>
    17           <Route exact path="/user" component={User}></Route>
    18         </Switch>
    19       </div>
    20     );
    21   }
    22 }
    23 
    24 export default withRouter(App);       //参数是一个组件,返回一个组件
     
    props.history.listen()
    只要是具备路由功能的组件都可以使用这个方法,参数接收一个回调函数,但是是有切换页面时才会触发这个方法,很像vue中的组件内的钩子,当路由变化的时候做一些事情

      props.history.listen((e) => {  console.log(e, '开启了withRouter')  }) 

  • 相关阅读:
    Unity SceneManager 对场景的操作
    Unity [Tooltip("")]
    Unity WWW下载图片并保存到Unity的Assets下
    C# 集合
    C# 枚举与switch用法
    C# String.Format方法
    C# Thread类 线程优先级
    Unity Gizmos可视化辅助工具
    anacanda
    异常和错误
  • 原文地址:https://www.cnblogs.com/shun1015/p/13571164.html
Copyright © 2011-2022 走看看