react withrouter的用法是什么

react withrouter的用法是什么,第1张

react withrouter的用法是什么

react withrouter用于将一个组件包裹进Route里面,并将“react-router”的三个history、location、match对象传入props对象,引入语法为“import{withRouter}from...”。

本教程 *** 作环境:Windows10系统、react17.0.1版、Dell G3电脑。

react withrouter的用法是什么

withRouter的作用就是, 如果我们某个东西不是一个Router, 但是我们要依靠它去跳转一个页面, 比如点击页面的logo, 返回首页, 这时候就可以使用withRouter来做.withRouter,

作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.(我的理解加上之后可以写编程时导航,不想vue可以在全局用this.$router.push()来完成)

将react-router 的 history、location、match 三个对象传入props对象

默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用 函数跳转 的写法,执行this.props.history.push('/detail')跳转到对应路由的页面

然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props

如何使用withRouter:

比如app.js这个页面,不是通过路由跳转过来的,而是直接从浏览器中输入地址打开的,如果不使用withRouter, 此组件的this.props为空,没法执行props中的history、location、match等方法, 如: 函数式跳转this.props.push('/detail')

设置withRouter很简单只需要两步:1引入, 2执行, 如下

import React,{Component} from 'react'
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' //引入withRouter
import One from './One'
import NotFound from './NotFound'
class App extends Component{
    //此时才能获取this.props,包含(history, match, location)三个对象
    console.log(this.props);  //输出{match: {…}, location: {…}, history: {…}, 等}
    render(){return (<div className='app'>
            <NavLink to='/one/users'>HOME</NavLink>
            <NavLink to='/one/companies'>OTHER</NavLink>
            <Switch>
                <Route path='/one/:type?' component={One} />
                <Redirect from='/' to='/one' exact />
                <Route component={NotFound} />
            </Switch>
        </div>)
    }
}
export default withRouter(App);  //这里要执行一下WithRouter

推荐学习:《react视频教程》

以上就是react withrouter的用法是什么的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/697438.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-22
下一篇 2022-04-22

发表评论

登录后才能评论

评论列表(0条)

保存