我是靠谱客的博主 执着金针菇,这篇文章主要介绍react withrouter的用法是什么,现在分享给大家,希望可以做个参考。

本教程操作环境: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执行, 如下

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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的用法是什么的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是执着金针菇最近收集整理的关于react withrouter的用法是什么的全部内容,更多相关react内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(116)

评论列表共有 0 条评论

立即
投稿
返回
顶部