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' //引入withrouterimport 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的用法是什么的详细内容。