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

如何通过点击事件修改React父组件Props值?结合componentWillUnmount实现

React状态提升结合componentWillUnmount的实现修正

原代码存在的问题

  • 父组件条件渲染错误:用了this.show而不是this.state.show,导致判断逻辑失效,子组件无法正确显示/隐藏
  • 子组件没必要把父组件传的方法存到自己state里:直接用props里的方法即可,存state可能导致方法不同步
  • render里直接执行alert:每次渲染都会弹出提示,属于没必要的副作用,调试用console更合适

修正后的代码

import React from 'react';

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state={
      show: true
    }
    // 将方法绑定到实例,避免每次render创建新函数
    this.toggleDisplay = () => {
      this.setState({show: !this.state.show});
    }
  }

  render() {
    return (
      <div className="App">
        {/* 修正条件渲染,使用state中的show值 */}
        {this.state.show && <ChildComponent onClick={this.toggleDisplay} />}
      </div>
    );
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log("constructor is called!");
  }

  render() {
    console.log("render is called!");
    return (
      <>
        <h1>This content is shown!</h1>
        {/* 直接调用props中的方法,无需存入子组件state */}
        <button onClick={this.props.onClick}>
          Toggle View
        </button>
      </>
    );
  }

  componentWillUnmount() {
    console.log("componentWillUnmount is called!");
    // 这里可以写卸载前的清理逻辑:比如取消网络请求、清除定时器、移除事件监听等
  }
}

核心逻辑说明

  • 状态提升:父组件App统一管理show状态,同时提供修改状态的方法toggleDisplay,通过props传递给子组件。子组件只负责触发这个方法,不用自己维护状态,实现了状态的统一管控,这就是React状态提升的核心思路。
  • componentWillUnmount触发:点击按钮后,父组件更新show为false,子组件不再被渲染,触发卸载流程,此时componentWillUnmount钩子执行,你可以在这里完成组件卸载前的收尾工作。

代码优化说明

  • 将toggleDisplay绑定到组件实例,避免在render中定义箭头函数导致每次渲染生成新的函数实例,提升性能。
  • 用console.log替代alert,避免alert阻塞页面渲染流程,调试体验更好。
  • 子组件直接使用props中的方法,确保方法始终是父组件最新的版本,避免状态不同步问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:13:11