页面scrollHeight变化或路由切换时如何重新渲染React组件?
解决CartModal组件路由切换时高度不更新的问题
针对你遇到的路由切换后scrollHeight不更新的问题,提供两种可行方案:
方案一:监听路由变化,更新state中的scrollHeight
通过React Router的withRouter高阶组件给组件注入路由信息,在路由切换时重新计算页面总高度并更新state:
- 首先导入
withRouter:
import { withRouter } from 'react-router-dom';
- 修改组件逻辑,添加路由监听和高度更新方法:
class CartModal extends Component { state = { scrollHeight: document.body.scrollHeight, }; componentDidMount() { // 初始化获取高度,同时监听窗口resize事件(可选) this.updateScrollHeight(); window.addEventListener('resize', this.updateScrollHeight); } componentDidUpdate(prevProps) { // 检测路由变化,更新高度 if (this.props.location !== prevProps.location) { this.updateScrollHeight(); } } componentWillUnmount() { // 移除resize监听,避免内存泄漏 window.removeEventListener('resize', this.updateScrollHeight); } updateScrollHeight = () => { this.setState({ scrollHeight: document.body.scrollHeight }); }; getContentHeight = () => { // 增加空值判断,避免找不到导航栏时报错 const navHeight = document.getElementById("navigation")?.clientHeight || 0; return this.state.scrollHeight - navHeight; }; render() { return createPortal( <div className={style.cartModal} style={{ height: `${this.getContentHeight()}px` }} > <Modal/> </div>, document.getElementById("modal") ); } } // 用withRouter包裹组件,注入路由props export default withRouter(CartModal);
方案二:实时计算高度,无需依赖state
直接在getContentHeight中实时获取最新的页面高度和导航栏高度,再通过路由变化触发组件重新渲染:
import { withRouter } from 'react-router-dom'; class CartModal extends Component { componentDidUpdate(prevProps) { // 路由切换时强制组件更新,触发render重新计算高度 if (this.props.location !== prevProps.location) { this.forceUpdate(); } } getContentHeight = () => { const scrollHeight = document.body.scrollHeight; const navHeight = document.getElementById("navigation")?.clientHeight || 0; return scrollHeight - navHeight; }; render() { return createPortal( <div className={style.cartModal} style={{ height: `${this.getContentHeight()}px` }} > <Modal/> </div>, document.getElementById("modal") ); } } export default withRouter(CartModal);
如果需要支持窗口resize场景,同样可以在componentDidMount中添加resize监听,调用forceUpdate即可。
内容的提问来源于stack exchange,提问作者Asifur Rahman
相关产品推荐
相关产品推荐

