前端踩坑(一)-----------react-router-dom讲解

贴上官网点击打开链接

react路由已经更新到4,网上的资料大多是旧版本,这里我们重点讲react-router-dom,它是用于dom绑定的react-router

常规导入

import React from 'react'

import { BrowserRouter as Router,Route,Link} from 'react-router-dom'

注意BrowserRouter只能有一个孩子,

switch用于重定向孩子为Route或者redirect

 ---从上向下匹配,只匹配它的第一个孩子

1.url带参数/参数

<Route path="/:id">

参数获取:this.props.match.params.id

2.带参数跳转该地址

<Link to={{

pathname:'/home' 路径名,

query:''    参数值

state:''   参数值保存在state中

}}   

a.query传参  this.props.location.query.xx 貌似刷新后该参数状态不会保存

b.state传参  this.props.location.state.xx

被Route包裹的组件会有location,match,history等属性,通过this.props获取即可

<Route path='/xx' component={组件}

若组件中又有子组件,父组件可属性方式将history等传递给子组件,子组件通过this.props获取

页面跳转

1.被Route包裹的组件,直接this.props.history.push("/xx")

2.普通组件可通过使用withRouter(组件)再this.props.history.push("/xx")

State

传递参数

state 方式类似于 post,依然可以传递任意类型的数据,而且可以不以明文方式传输。

使用 router.push 跳转页面 , 传递参数 将参数-> commentid, headimgurl存放到 state

router.push({ pathname: './authenticate/info', state: { commentid, headimgurl} });

使用 this.props.location.state 解构出参数 , 使用

const {commentid,headimgurl} = this.props.location.state;

query

query 方式可以传递任意类型的值,但是页面的 url 也是由 query 的值拼接的,url 很长且是明文传输。

//定义路由
<Route path='/user' component={UserPage}></Route>
 
//数据定义
let data = {id:3,name:sam,age:36};
let path = {
    pathname: '/user',
    query: data,
}
 
//页面跳转
<Link to={path}>用户</Link>
this.props.history.push(path);
 
//页面取值
let data = this.props.location.query;
let {id,name,age} = data;

API

export interface RouteData { pathname: string, query?: any, search?: string, state?: any }
​
declare const router: {
  push: (path: string | RouteData) => void;
  replace: (path: string | RouteData) => void;
  go: (count: number) => void;
  goBack: () => void;
}
export default router;

参考文章

https://juejin.im/entry/5b50518bf265da0f6436c34a

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值