React Router DOM 5.x:URL查询参数变更时触发组件重渲染
在react-router-dom 5.x中监听URL查询参数变化触发组件重渲染的方案
下面提供两种适配不同组件类型的解决方案:
函数组件:使用useLocation钩子
利用useLocation返回的location对象会在路由(包括查询参数)变化时更新的特性,结合useEffect监听location.search的变化:
import { useLocation, Link } from 'react-router-dom'; import { useEffect } from 'react'; function LocationsComponent() { const location = useLocation(); useEffect(() => { // 解析URL查询参数 const searchParams = new URLSearchParams(location.search); const shouldOpenModal = searchParams.get('openCertainModal') === 'true'; // 这里执行你需要的逻辑,比如打开模态框 if (shouldOpenModal) { // 处理模态框打开的相关操作 } }, [location.search]); // 仅当search参数变化时触发回调 return ( <Link to={`/route/locations?openCertainModal=true`}>打开指定模态框</Link> ); } export default LocationsComponent;
类组件:使用withRouter高阶组件
通过withRouter给类组件注入路由相关的props,在componentDidUpdate中对比前后的location.search值,判断是否需要触发逻辑:
import { withRouter, Link } from 'react-router-dom'; import React from 'react'; class LocationsComponent extends React.Component { componentDidUpdate(prevProps) { // 检测查询参数是否发生变化 if (this.props.location.search !== prevProps.location.search) { const searchParams = new URLSearchParams(this.props.location.search); const shouldOpenModal = searchParams.get('openCertainModal') === 'true'; if (shouldOpenModal) { // 执行模态框打开等业务逻辑 } } } render() { return ( <Link to={`/route/locations?openCertainModal=true`}>打开指定模态框</Link> ); } } // 用withRouter包裹组件,注入location、history等路由属性 export default withRouter(LocationsComponent);
注意:不建议直接监听
window.popstate事件,因为React Router已经封装了路由状态的管理,使用上述方案更符合React的组件生命周期和路由生态。
内容的提问来源于stack exchange,提问作者GABRIEL R GARCIA-AVILES
相关产品推荐
相关产品推荐

