简体   繁体   中英

How do you remount a component in reactjs?

I have a component that I need to re-mount. I need to destroy everything and make it's code re-execute to appear again on my page.

What I've tried: I put key="1" and then with javascript changed its key to something else, it did not remount ( https://groups.google.com/forum/#!topic/reactjs/8JgClU9jol0 )

Unmounting React.js node this won't work because my component is already rendered.

Please help, how do I do this?

Here is an example.

 class Child extends React.Component { componentDidMount = () => { console.log("mounted"); } render(){ return( <div>This is child</div> ); } } class Application extends React.Component { state = { show: true, }; render(){ return( <div> <button onClick={() => this.setState({show: !this.state.show})}>Click here</button> {this.state.show && <Child />} </div> ); } } ReactDOM.render(<Application />, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM