react-router-dom基本使用+3种传参方式
//App.js
import {
BrowserRouter as Router,
Route,
Link,
} from "react-router-dom";
// 引入组件
import Home from "....";
import News from "...."
function App() {
return (
<Router>
<Link to="/">首页</Link>
<Link to="/news">新闻</Link>
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
</Router>
);
}
export defautl App;
如何传递参数(3种)
1、params传参(动态路由)
特点:刷新页面参数不消失,参数会在地址栏显示
- 路由配置
<Route path='/about/:id' component={About} />
- 跳转方式
//传递参数可以拆分为对象写法:{pathname:'/about/3'}
//html:
<Link to={'/about/3'}>点击跳转</Link>
//js:
this.props.history.push('/about/3')
- 获取值
this.props.match.params.id // 3
2、query传参
特点:刷新页面参数消失,参数不会在地址栏显示
- 路由配置
<Route path='/about' component={About} />
- 跳转方式
//html:
<Link to={{pathname:'/about', query:{id:3}}}>点击跳转</Link>
//js:
this.props.history.push({pathname:'/about', query:{id:3}})
- 获取值
this.props.location.query.id // 3
3、state传参
特点:刷新页面参数不消失,参数不会在地址栏显示
- 路由配置
<Route path='/about' component={About} />
- 跳转方式
//html:
<Link to={{pathname:'/about', state:{id:3}}}>点击跳转</Link>
//js:
this.props.history.push({pathname:'/about', state:{id:3}})
- 获取值
this.props.location.state.id // 3