贴上官网点击打开链接
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