import React, { Component } from "react";
import { browserRouter, Link, Switch, Route, Redirect } from "react-router-dom";
import About from "./pages/About";
import Main from "./pages/Main"; //路由组件,放在pags文件夹
export default class App extends Component {
render() {
return (
<div className="flex-row-center">
<browserRouter>
<div style={{ marginRight: 20 }}>
{/* ----------------------传params参数------------------------- */}
<Link to="/about/hguan/18">About</Link>
{/* ----------------------传search参数------------------------- */}
<Link to="/main/?name=hguan&age=18">Main</Link>
{/* ----------------------传state参数-------------------------- */}
<Link
to={{ pathname: "/about", state: { name: "hguan", age: 18 } }}
></Link>
</div>
<div>
<Switch>
{/* ====================声明接收params参数================== */}
<Route path="/about/:name/:age" component={About} />
{/* ==================search参数无需声明接收================= */}
{/* ================= state参数无需声明接收================== */}
<Route path="/main" component={Main} />
<Redirect to="/main" />
</Switch>
</div>
</browserRouter>
</div>
);
}
}
/**
* ”路由跳转“ 的工作原理:就是对history历史记录进行操作
* push模式 将路径压入history栈,留痕 ------- 默认
* (1).声明式导航:<Link to="/test" />
* (2).编程式导航:this.props.history.push("/test");
*
* replace模式 切换路由时替换路径,无痕
* (1).声明式导航:<Link replace to="/test" />
* (2).编程式导航:this.props.history.replace("/test");
*/
/**
* 路由组件传参:
* 方法一. 传递params参数:
*
* (1)传参:
* 声明式导航:<Link to="/about/hguan/26">关于</Link>
* 编程式导航: this.props.history.push("/about/hguan/26");
* (2)声明:<Route path="/about/:name/:age" component={About} />
* (3)组件接收: const {name,age} = this.props.match.params 格式为对象{name:hguan,age:18}
*
* 方法二: 传递search参数:
*
* (1)传参:
* 声明式导航:<Link to="/about/?name=hguan&age=26" >关于</Link>
* 编程式导航: this.props.history.push("/about/?name=hguan&age=26");
* (2)声明:(无需声明,正常注册即可) <Route path="/about" component={About} />
* (3)组件接收: const urlStr = this.props.location.search 格式为字符串‘?name=hguan&age=26’
* const {name,age}=qs.parse(urlStr.slice(1));
*
* >>> 补充:这种key=value&key=value的编码形式叫做urlencoded编码;
* import qs from "qureystring";(脚手架自带)
* qs.stringify(对象) //将对象转为urlencoded编码
* qs.parse(urlencoded编码) //将urlencoded编码转为对象
*
* 方法三: 传递state参数:
*
* (1)传参:
* 声明式导航:<Link to={{ pathname: "/about", state: { name: "hguan", age: 26 } }}>关于</Link>
* 编程式导航: this.props.history.push("/about",{ name: "hguan", age: 26 });
* (2)声明:(无需声明,正常注册即可) <Route path="/about" component={About} />
* (3)组件接收: const {name,age} = this.props.location.state 格式为对象{name:hguan,age:26}
*/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。