You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面scrollHeight变化或路由切换时如何重新渲染React组件?

解决CartModal组件路由切换时高度不更新的问题

针对你遇到的路由切换后scrollHeight不更新的问题,提供两种可行方案:

方案一:监听路由变化,更新state中的scrollHeight

通过React Router的withRouter高阶组件给组件注入路由信息,在路由切换时重新计算页面总高度并更新state:

  1. 首先导入withRouter:
import { withRouter } from 'react-router-dom';
  1. 修改组件逻辑,添加路由监听和高度更新方法:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:45:37