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

如何阻止React组件的componentDidMount生命周期函数被重复调用两次?

解决componentDidMount被调用两次的方案

常见触发原因及对应解决方法

  • React 18 开发环境严格模式触发
    React 18 的<StrictMode>在开发环境下会故意执行「挂载-卸载-重新挂载」的流程,模拟生产环境下组件可能被复用的场景,因此会触发两次componentDidMount,该问题在生产环境会自动消失。
    临时规避可以在组件内添加实例变量标记执行状态,避免逻辑重复执行,适配后代码如下:
    class BarSearchFormComponent extends Component {
      constructor(props) {
        super(props);
        this.searchInput = React.createRef();
        this.onChange = this.onChange.bind(this);
        this.onKeyDown = this.onKeyDown.bind(this);
        this.state = { keywords: null, inputValue: '' };
        // 新增挂载状态标记
        this.hasExecutedMountLogic = false;
      }
    
      componentDidMount() {
        // 已执行过则直接跳过
        if (this.hasExecutedMountLogic) return;
        this.hasExecutedMountLogic = true;
        const value = queryString.parse(window.location.search);
        const { keywords } = value;
        this.setState({ inputValue: keywords });
      }
    
      // 剩余原有逻辑不变
      onKeyDown(e) {
        if (e.keyCode === KEY_CODE_ENTER) {
          this.props.onSubmit({ keywords: this.state.keywords })
          if (this.searchInput.current) {
            this.searchInput.current.blur();
          }
        }
      }
      onChange(keywords) {
        this.setState({ keywords: keywords }, () => {
          this.setState({ inputValue: this.state.keywords });
        });
      }
    
      render() {
        const { right } = this.props;
        return (
          <FinalForm
          // 原有渲染逻辑不变
    
  • 父组件逻辑导致子组件销毁重建
    检查父组件渲染当前搜索组件时的逻辑:
    1. 是否给组件设置了动态变化的key属性,key变化会触发组件销毁重建
    2. 是否存在条件渲染逻辑,状态切换时会把当前组件移除后重新插入DOM
      修复对应逻辑、固定组件key即可解决。
  • 组件被多次实例化
    检查页面结构,是否在多个位置都引入渲染了BarSearchFormComponent组件,移除多余的实例即可。

搜索关键词展示场景优化建议

你当前的需求是展示用户已搜索的关键词,无需将url参数存储到组件内部state,可以直接在渲染时读取url参数,彻底规避生命周期触发次数的影响:

render() {
  const { right } = this.props;
  const { keywords } = queryString.parse(window.location.search);
  // 直接把keywords赋值给输入框的value即可,不需要维护inputValue状态
}

内容的提问来源于stack exchange,提问作者Rehab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:24:01