您现在的位置是:网站首页> 编程资料编程资料

React路由组件三种传参方式分析讲解_React_

2023-05-24 327人已围观

简介 React路由组件三种传参方式分析讲解_React_

路由组件和组件的区别

路由组件时被Router组件使用的组件,this.props里面有三个参数,分别是history、match、location

可以接收到路由跳转传参,也可以进行编程式导航跳转

普通组件只有父传子的props值

Swith内置组件使用

作用:当匹配一个路由组件时,其他组件不会被使用,可以加入404页面,给用户进行友好提示,提升用户体验

react 路由传参

方式一:url的query方式传参,在App组件中

//传值 主页面 //接收 

如果我们要打印我们接收到的值,有两种方式

第一种,在home组件中,创建一个生命周期,然后进行普通的切割、添加、打印即可

 componentDidMount(){ console.log(this.props.history.location.search); let a=this.props.history.location.search.slice(1) let b=a.split('&') console.log(b); let obj={} b.forEach((item)=>{ item.split('=') obj[item.split('=')[0]]=item.split('=')[1] }) console.log(obj); }

第二种:使用querystring,在使用之前,需要下载引入

下载:npm i querystring -D

 componentDidMount(){ let a=this.props.history.location.search.slice(1) console.log(querystring.parse(a)); }

在页面使用:querystring.parse(url形式携带的字符串)

方式二:url的params传参

//传值 登录 //接收 

注意:传入的参数跟值得长度必须一致,否则会报错

打印:

 componentDidMount(){ // console.log(this.props); console.log(this.props.match.params); }

方式三:

//传值 注册页面 //接收 

打印:

componentDidMount(){ console.log(this.props.location.user); }

编程式导航

我们定义一个按钮,在按钮中给他一个点击事件,在事件函数中我们进行路由得跳转

home组件

export default class home extends Component { onchange=()=>{ this.props.history.push('/home/?name=张三&age=19') } render() { return ( 
) } }

在home 组件中,this.props.history.push后面跟上边三种传参方式

app组件

主页面

Redirect重定向

跟我们vue中的redirect使用方法相似,用来路由跳转

到此这篇关于React路由组件三种传参方式分析讲解的文章就介绍到这了,更多相关React路由组件传参内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网