【问题标题】:rerender React js component重新渲染 React js 组件
【发布时间】:2016-01-11 04:34:07
【问题描述】:

我必须使用 React js 为现有应用程序实现新的 UI。这是单击菜单项后呈现的反应组件。我注意到用于 react 的 chrome 开发工具插件会在每次单击菜单时显示创建的新组件。 不是浪费内存吗? 这是 Sammy.js 的菜单激活码

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

【问题讨论】:

    标签: javascript reactjs rerender


    【解决方案1】:

    是的,您应该只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>
        );
      }
    });
    

    【讨论】:

    • 好的,但是点击其他菜单项内容页面后会被覆盖,所以如果我点击返回上一个菜单项,我需要再次重新渲染。
    【解决方案2】:

    根据React top-level API documentation

    如果 ReactElement 之前被渲染到容器中,这将对它执行更新,并且只在必要时改变 DOM 以反映最新的 React 组件。

    所以重新渲染不应该创建一个新的组件,而是更新之前的组件。

    根据您的用例,您可能希望处理 React 应用程序或组件内的菜单单击,并在内部更新状态并重新渲染,但这在您的情况下可能是不可能的。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-12-29
        • 2021-06-19
        • 2018-04-22
        • 1970-01-01
        • 2020-03-22
        • 2020-08-18
        • 2021-01-19
        • 2020-05-01
        相关资源
        最近更新 更多