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

React子组件componentWillUnmount中如何获取最新props?

如何在React组件卸载时获取更新后的props

当前场景中,父组件通过id ===1的条件渲染Child组件,点击按钮将id更新为2后,Child直接被卸载,但此时componentWillUnmount中只能拿到旧的props(id=1),需求是在卸载时获取到更新后的id=2。

问题根源

当父组件id变为2时,条件id ===1不成立,React会直接从渲染树中移除Child组件,Child没有机会接收新的props就被卸载,因此componentWillUnmount里的props还是更新前的旧值。

解决方案:让Child先接收新props再卸载

要实现需求,必须调整渲染逻辑,让Child在卸载前先完成props更新的生命周期,再触发卸载。以下提供两种可行方案:

方案一:父组件分两步更新状态

通过额外的状态控制Child的显示,先更新id让Child接收新props,再延迟卸载Child:

父组件修改后代码:

import React, { useState } from 'react';
import Child from './Child.jsx'
export function App(props) {
  const [id, setId] = useState(1);
  const [showChild, setShowChild] = useState(true);

  const handleClick = () => {
    // 第一步:更新id,让Child接收新的props
    setId(2);
    // 第二步:在下一次渲染周期后触发卸载
    setTimeout(() => {
      setShowChild(false);
    }, 0);
  }

  return (
    <div className='App'>
      <h1>Hello React.</h1>
      {showChild && <Child id={id} onUnmount={() => setShowChild(false)} />}
      <button onClick={handleClick}>change value</button>
    </div>
  );
}

子组件修改后代码:

import React from 'react';

export default class Child extends React.Component {
  componentDidUpdate(prevProps) {
    // 检测到id更新为2时,通知父组件卸载自己
    if (this.props.id === 2 && prevProps.id === 1) {
      this.props.onUnmount();
    }
  }

  componentWillUnmount() {
    console.log('卸载时的id:', this.props.id); // 输出2
  }

  render() {
    return <div>Child</div>;
  }
}

方案二:子组件自行控制渲染状态

父组件始终渲染Child,由Child根据props变化决定是否卸载自己:

父组件修改后代码:

import React, { useState } from 'react';
import Child from './Child.jsx'
export function App(props) {
  const [id, setId] = useState(1);

  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <Child id={id} />
      <button onClick={() => setId(2)}>change value</button>
    </div>
  );
}

子组件修改后代码:

import React from 'react';

export default class Child extends React.Component {
  state = { shouldRender: true };

  componentDidUpdate(prevProps) {
    // 当id变为2时,设置不渲染,触发卸载
    if (this.props.id === 2 && prevProps.id === 1) {
      this.setState({ shouldRender: false });
    }
  }

  componentWillUnmount() {
    console.log('卸载时的id:', this.props.id); // 输出2
  }

  render() {
    if (!this.state.shouldRender) return null;
    return <div>Child</div>;
  }
}

原理说明

两种方案的核心都是让Child组件先经历componentDidUpdate生命周期,接收到更新后的id=2 props,再触发卸载操作,这样componentWillUnmount中就能获取到最新的props值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:32:55