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

React子组件点击删除时如何触发父类组件的componentDidUpdate生命周期

核心实现逻辑

先修复父组件现有问题

你的父组件现有两处明显问题会先导致逻辑异常:

  1. 拼写错误:构造函数名construction应为constructor;componentDidUpdate中判断用的this.state.ObjectList大小写错误,和state里定义的objectList不一致
  2. 无限循环问题:componentDidUpdate中判断objectList变化后又调用getObjectList,而getObjectList会调用setState修改objectList,再次触发componentDidUpdate,形成死循环,这部分逻辑直接删除即可。

父子组件通信实现

通过props将父组件的列表刷新方法传递给子组件,子组件删除成功后调用该方法触发父组件状态更新,自然会触发componentDidUpdate生命周期。


完整修改代码

父组件 ListOfItems.js

class ListOfItems extends Component {
  constructor (props) {
    super(props);
    this.state = {
      objectList: []
    }
  }

  // 拉取要展示的对象列表
  componentDidMount() {
     this.getObjectList();
  }

  componentDidUpdate(_prevProps, prevState) {
    // 按需添加你自己的业务逻辑即可
    console.log("componentDidUpdate 已触发");
  }

  getObjectList = () => {
    const input = { id_for_this_list: id }

    fetch( connectToApi, {
       method: "PUT",
       headers: { /* stuff */ },
       body: JSON.stringify(input)
    })
       .then(res => /* 你的响应处理逻辑 */)
       .then(result => {
          if( result.length >= 0) {
              this.setState({ objectList: result });
          }   
       })
       .catch(err=>{console.error(err)});
  }

  render () {
    return (
      this.state.objectList.map(item => (
        <Object 
          objectList={this.state.objectList}
          data={item}
          onDeleteSuccess={this.getObjectList} {/* 新增传递刷新回调 */}
          // 其他props
        />
      ))
    )
  }
}

子组件 Object.js

// 接收父组件传入的回调props
const Object = ({ onDeleteSuccess }) => {
  const deleteObject = () => {
     fetch( connectToApi, {
       method: "DELETE"
     })
        .then(res => /* 你的响应处理逻辑 */)
        .then(result => {
          // 确认删除成功后调用父组件传入的刷新方法
          onDeleteSuccess()
        })
        .catch(err => console.error(err))
  }

  return <img onClick={() => deleteObject()} alt="删除图标" />
}

触发逻辑说明

子组件删除接口请求成功后调用onDeleteSuccess,会触发父组件重新拉取列表,setState更新objectList后父组件重新渲染,自动触发componentDidUpdate生命周期,完全符合你的项目约束要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:24:03