• 技术文章 >web前端 >前端问答

    react withrouter的用法是什么

    长期闲置长期闲置2022-04-19 11:05:57原创173

    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的用法是什么的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:React
    上一篇:react dnd的用法是什么 下一篇:什么时候使用react-redux
    Web大前端开发直播班

    相关文章推荐

    • 聊聊怎么利用Memoization提高React性能• react项目中如何运行vue组件?方法介绍• react高阶组件是什么意思• react中hook是什么• react15与16版本的不同是什么

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网