• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

React卸载组件

武飞扬头像
士女士女子
帮助1

在React18之前,卸载组件可以用ReactDOM中的unmountComponentAtNode来解决

  1.  
    import ReactDOM from 'react-dom';
  2.  
    unmount = () => {
  3.  
    ReactDOM.unmountComponentAtNode(document.getElementById('root'));
  4.  
    }

但是删除节点 unmountComponentAtNode(),在React18中被root.unmount()所取代。

1.首先在index.js入口文件中,将root暴露出去

export const root = ReactDOM.createRoot(document.getElementById('root'));

2.在要卸载组件的文件中,引入root,并调用unmount()方法

类式组件:

  1.  
    import {root} from '../../index'
  2.  
     
  3.  
    class Demo extends React.Component {
  4.  
    unmount = () => {
  5.  
    root.unmount();
  6.  
    }
  7.  
    componentWillUnmount() {
  8.  
    clearInterval(this.timer)
  9.  
    }
  10.  
    render() {
  11.  
    return (
  12.  
    <div>
  13.  
    <button onClick={this.unmount}>点我卸载组件</button>
  14.  
    </div>
  15.  
    )
  16.  
    }
  17.  
    }
学新通

函数式组件:

  1.  
    import {root} from '../../index'
  2.  
    //函数式组件
  3.  
    function Demo() {
  4.  
    React.useEffect(() => {
  5.  
    return () => {
  6.  
    clearInterval(timer);
  7.  
    }
  8.  
    },[])
  9.  
     
  10.  
    //卸载组件的回调
  11.  
    function unmount() {
  12.  
    root.unmount();
  13.  
    }
  14.  
    return(
  15.  
    <div>
  16.  
    <button onClick={unmount}>点我卸载组件</button>
  17.  
    </div>
  18.  
    )
  19.  
    }
  20.  
    export default Demo
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbegcb
系列文章
更多 icon
同类精品
更多 icon
继续加载