React dom什么时候被销毁?

第一次实例化的时候组件被装载到了dom里,后面state和props改变的时候重新触发render函数,如果现在render里面是两个完全不同的dom(第一次是if里的语句,后面是else里的语句),第一次的dom去了哪里?是被销毁了吗?为什么不调用componentWillUnmount?

阅读 8.8k
2 个回答

你的问题是当执行重渲染时,之前的渲染的dom去了哪里?是被销毁了吗?

看要用什么角度看,与你用的结构也有关:

  • 对真实网页dom结构上来说是被销毁了,不存在了。

  • 如果你的dom是用state保存住,至少会保留现在这一份与上一份在state里,超过就没了。没用state保存就GC(垃圾回收)去了,最后剩下只有存在代码里的变量中。

  • 如果你的dom是用redux之类的store保存住,那么在应用执行期间,一直都会在store里,因为这是redux时光旅行的设计,有用过你就会知道了。

为什么不调用componentWillUnmount?

因为componentWillUnmount是生命周期方法,它不是用来卸载(Unmount)组件用的,它是在组件要卸载前,让你可以再多作某些事情用的。也就是说,卸载(Unmount)组件这件事,是React帮你作的,要进行卸载(Unmount)组件前,React会问你,还有什么要作的,你写在这里告诉React就是,他会自动调用,其他的生命周期方法也是类似的设计。

不知道你的结论从何得出的,重新渲染,componentWillUnmount是执行的

import React from 'react';
import ReactDOM from 'react-dom';

class A extends React.Component {
  componentWillUnmount() {
    console.log('A unmount');
  }

  render() {
    return <p>A Component</p>;
  }
}

class B extends React.Component {
  componentWillUnmount() {
    console.log('B unmount');
  }

  render() {
    return <p>B Component</p>;
  }
}

class App extends React.Component {

  constructor() {
    super();

    this.state = {
      show: true
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({show: !this.state.show});
  }

  render() {
    return <div onClick={this.handleClick}>
      {this.state.show ? <A /> : <B />}
    </div>;
  }
}

ReactDOM.render(
  <App/>,
  document.getElementById('app')
);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题