ReactJS - Destroy old Component-Instance and create new

前端 未结 1 1473
遇见更好的自我
遇见更好的自我 2021-02-20 02:36

I\'ve got a may confusing question because it does not fit standard-behaviour how react and the virtual dom works but i would like to know the answer anyway.

Imagine i\'

相关标签:
1条回答
  • 2021-02-20 03:10

    If you give the component a key, and change that key when re-rendering, the old component instance will unmount and the new one will mount:

    render() {
      ++this.childKey;
      return <Container>
        <div id="wrappingDiv">
          <ChildContainer key={this.childKey}/>
        </div>
      </Container>;
    }
    

    The child will have a new key each time, so React will assume it's part of a list and throw away the old one, creating the new one. Any state change in your component that causes it to re-render will force that unmount-and-recreated behavior on the child.

    Live Example:

    class Container extends React.Component {
      render() {
        return <div>{this.props.children}</div>;
      }
    }
    
    class ChildContainer extends React.Component {
      render() {
        return <div>The child container</div>;
      }
      componentDidMount() {
        console.log("componentDidMount");
      }
      componentWillUnmount() {
        console.log("componentWillUnmount");
      }
    }
    
    class Example extends React.Component {
      constructor(...args) {
        super(...args);
        this.childKey = 0;
        this.state = {
          something: true
        };
      }
    
      componentDidMount() {
        let timer = setInterval(() => {
          this.setState(({something}) => ({something: !something}));
        }, 1000);
        setTimeout(() => {
          clearInterval(timer);
          timer = 0;
        }, 10000);
      }
      
      render() {
        ++this.childKey;
        return <Container>
          {this.state.something}
          <div id="wrappingDiv">
            <ChildContainer key={this.childKey}/>
          </div>
        </Container>;
      }
    }
    
    ReactDOM.render(
      <Example />,
      document.getElementById("root")
    );
    <div id="root"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>


    Having said that, there may well be a better answer to your underlying issue with the plugin. But the above addresses the question actually asked... :-)

    0 讨论(0)
提交回复
热议问题