ReactRouter5
1、Params 方式
特点:参数只能是字符串,直接显示在地址栏上,Route中需要提前占位,刷新页面后参数不丢失。
第一步: 使用Link导航或NavLink导航
<Link to={`/home/message/detail/${item.id}}/${item.title}}`}>{item.title}</Link>
第二步: 在路由规则 Route 的 path 中定义参数名称
<Route path="/home/message/detail/:id/:title" component={Detail}></Route>
第三步: 在路由组件中,我们通过props来获取参数,props中包含history,location,match
const { id, title } = this.props.match.params
2、Search 方式
特点:和Vue中的query方式比较类似,Route中不需要提前占位。
第一步: 使用Link或NavLink导航
<Link to={`/home/message/detail/?id=${item.id}&title=${item.title}`}>{item.title}</Link>
第二步: 在Route定义规则
<Route path="/home/message/detail" component={Detail}></Route>
第三步: 在路由组件中,通过props来获取参数
let msg = new URLSearchParams(this.props.location.search.slice(1))
This is detail id:{msg.get('id')}---title:{msg.get('title')}
3、State 方式
特点:参数可以是对象,不显示在地址栏上,刷新后参数不丢失
第一步: 使用Link或NavLink导航,传递state对象
<Link to={{ pathname: '/home/message/detail', state: { id: item.id, title: item.title } }}>{item.title}</Link>
第二步: 在Route定义规则
<Route path="/home/message/detail" component={Detail}></Route>
第三步: 在路由组件中获取参数
const { id, title } = this.props.location.state || {};
最后5.x版本中需要注意的是:当我们在5.x版本中使用函数式组件时,通过路由来传递参数,我们需要使用withRouterAPI来渲染一般组件,使得组件具有history,location,match属性,这样我们才能正常的进行路由传参
ReactRouter6
与5.x版本主要的区别:
- 内置组件的变化:移除Switch,Redirect,新增Routes,Navigate
- 语法的变化:component={About} 变为 element={< About />}
- 新增了多个hook函数:useParams,useNavigate,useMatch,useRoutes等
- 官方明确推荐使用函数式组件
路由传参
主要的变化是在路由组件当中:
1、使用useParams来获取params参数
const { id, context } = useParams();
2、使用useSearchParams来获取search参数,useLocaiton也可以
const [search, setSearch] = useSearchParams();
This is news page---id:{search.get('id')}---context:{search.get('context')}
3、使用useLocation来获取state参数
const { id, context } = useLocation().state;