ReactJS - Destroy old Component-Instance and create new

前端 未结 1 1462
遇见更好的自我
遇见更好的自我 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 
        
    ; }

    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 
    {this.props.children}
    ; } } class ChildContainer extends React.Component { render() { return
    The child container
    ; } 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 {this.state.something}
    ; } } ReactDOM.render( , document.getElementById("root") );


    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)
提交回复
热议问题