简体   繁体   中英

rerender React js component

I have to implement new UI to existing application with React js. This is react component which is rendered after menu item is clicked. I noticed that chrome dev tools plugin for react shows new component created each time the menu is clicked. Isn't it waste of memory? this is menu activation code by Sammy.js

this.get('#/security',function(){
        this.swap("");
        React.render(
           <MainComponent/>,
           document.getElementById('content')
       );
    });

Yea you should only React.render once. Try something like:

React.render(<App />, document.getElementById('content'));

const App = React.createClass({
  getInitialState() {
    return { loaded: false };
  },

  componentDidMount() {
    this.get('#/security',function(){
      this.swap("");
      this.setState({ loaded: true });  
    });
  },

  render() {
    return (
      <div>
        {this.state.loaded ? <MainComponent /> : null}
      </div>
    );
  }
});

According to the React top-level API documentation :

If the ReactElement was previously rendered into container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.

So re-rendering shouldn't create a new component, but rather update the previous one.

Depending on your use-case you may want to handle the menu click inside your React app or component and update state internally and re-render, but that may not be possible in your case.

状态更改后的forceUpdate()可能会解决手动渲染组件的问题。

  this.forceUpdate();//manually renders components of each time the state changed

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