簡體   English   中英

重新渲染React js組件

[英]rerender React js component

我必須使用React js為現有應用程序實現新的UI。 這是在單擊菜單項后呈現的react組件。 我注意到,每次點擊菜單時,用於響應的chrome dev工具插件都會顯示新創建的組件。 這不是浪費內存嗎? 這是Sammy.js的菜單激活代碼

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

是的,您只React.render一次React.render 嘗試類似:

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>
    );
  }
});

根據React頂層API文檔

如果以前將ReactElement渲染到容器中,它將對它執行更新,並且僅在必要時對DOM進行更改以反映最新的React組件。

因此,重新渲染不應創建新組件,而應更新前一個組件。

根據您的用例,您可能需要處理菜單在React應用程序或組件中單擊並在內部更新狀態並重新呈現,但是在您的情況下可能無法實現。

狀態更改后的forceUpdate()可能會解決手動渲染組件的問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM