React 学习笔记

805 阅读1分钟

React v16

unmountComponentAtNode

ReactDOM.unmountComponentAtNode 方法只能销毁 ReactDOM.render的组件节点,不能销毁React组件里render生成的节点;

先定义一个子组件

//子组件
class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: props.value
        };
    }
    render() {
        return (
            <div> {this.state.value} </div>
        );
    }
}

父组件里,错误使用案例

//父组件
class ParentBox extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
      //此处使用unmountComponentAtNode是无效的;
      const childDiv = ReactDOM.findDOMNode(this.refs.childDiv);
      ReactDOM.unmountComponentAtNode(childDiv);
    }
    componentWillUnmount() {
    }
    render() {
        return (
            <Child value={'Loading...'} ref={'childDiv'} />
        );
    }
}

父组件里,正确使用

//父组件
class ParentBox extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
      //先定义一个Child子组件,此处设置ref会报错
      ReactDOM.render(<Child id={'childDiv2'} value={'123'}/>, document.getElementById('childBox'));
      //删除子组件,此处使用unmountComponentAtNode有效  
      ReactDOM.unmountComponentAtNode(document.getElementById('childBox'));
    }
    componentWillUnmount() {
    }
    render() {
        return (
            <div>
                 {/*<Child value={'Loading...'} ref={'childDiv'} />*/}
      
                 <div id={'childBox'} />  
            </div>  
        );
    }
}

参考:github.com/itbilu/reac…