You need to enable JavaScript to run this app. React子组件id props变更时componentDidUpdate与render均未触发问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React子组件id props变更时componentDidUpdate与render均未触发问题求助

React 类组件更新异常问题

相关代码

class ParentComponent extends Component {
  constructor() {
    super()

    this.state = {
      id: null,
    }
}

  render() {
    const dataTarged = "#col" + id
    const id = "col" + id
    return (
      <React.Fragment>
        <div>
          <button data-toggle="collapse" data-target={dataTarged} onClick={() => this.setState({ id: <<this id may vary>> })}>Click me</button>
        </div>

        <div className="collapse mt-4" id={id}>
          <ChildComponent id={this.state.id} />
        </div>
      </React.Fragment>
    )
  }
}


class ChildComponent extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.id != prevProps.id) {
      //do stuff with the ID
    }
  }
}

代码逻辑说明

  • 父组件实现折叠面板交互逻辑,折叠面板内部通过this.state.id(取值可变)向子组件传递id参数
  • 点击按钮时会同时触发折叠面板的展开/收起切换,将携带最新props的ChildComponent展示出来

运行场景

  • 父组件为卡片形态,页面中存在多个不同id的该类父组件实例
  • 每次点击按钮时,父组件的state会更新为对应场景的新id值,并将该值作为props传递给ChildComponent

异常问题描述

  • 切换不同父组件时,ChildComponent中的componentDidUpdate钩子会停止被调用,传入的id无法正常更新,依赖该id获取的业务信息不符合预期
  • ChildComponent的render函数也没有被触发,组件完成首次渲染后就不会再重新执行渲染逻辑

按照React的运行规则,传入ChildComponent的props发生变化时理应触发componentDidUpdate钩子,每次切换不同父组件时都变更了传入的props值,为什么没有触发更新逻辑?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.21 05:36:03