1. 动态路由传参
// 1.配置占位
<HashRouter>
<Switch>
<Route path="/xxx/:id"></Route> //留好占位
</Switch>
</HashRouter>
// 2.参数传递
import useHistory from 'react-router-dom'
const historty = useHistory()
let id = 6666;
history.push(`/xxx/${id}`);
// 3.接收参数
let param = props.match.param.id;
console.log(param)
2. query传参
- 优点:传参优雅,传递参数可传对象;
- 缺点:刷新地址栏,参数丢失。
// 1.参数传递
import useHistory from 'react-router-dom'
const historty = useHistory()
history.push({ pathname: '/xxxx', query: { id: 666} });
// 2.接收参数
console.log(props.location.query.id)
3. search传参
- 优点:页面刷新,参数不会丢失;
- 缺点:传值太多url也会变的很长。
// 1.参数传递
import useHistory from 'react-router-dom'
const historty = useHistory()
history.push({ pathname: '/xxxx', state: { id: 666} });
// 2.接收参数
console.log(props.location.state.id)