【问题标题】:Is my React component being recreated instead of updating?我的 React 组件是否被重新创建而不是更新?
【发布时间】:2014-08-16 00:13:28
【问题描述】:

我正在尝试将 Angular 和 React.js 结合起来。我有一个工作示例项目here 我已经看到了几种将 Angular 和 React.js 结合在一起的方法。我见过的一种方法是创建指令并在链接函数中创建 React 组件。例如在项目的第一部分生成我正在使用的 React 版本(红色)

.directive('reactElementRepeater', function() {
    return {
      link: function(scope, element) {
        var update_react = function(oldVal, newVal){ //Called every time one of the two values change
          React.renderComponent(Demo_Element({
            numberOfElements: scope.myModel.numberOfElem, 
            numberInElements: scope.myModel.numberInElem
          }), element[0]);
        }
        scope.$watch('myModel.numberOfElem.length', update_react);
        scope.$watch('myModel.numberInElem', update_react);
      }
    }
  });

我想要并且在启用 React 的应用程序中应该发生的事情是更新模型中的某些内容,然后通过 React 发送更新,并且它将尽可能少地更改 DOM 以反映该更改。看起来这不是更新一些 DOM,而是每次使用 renderComponent 创建一个新的 React 组件。

React.renderComponent() instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument.

实际上每次都在重新创建元素吗?如果是这种情况,有没有办法改变这种情况,这样就不会发生? 为了清楚起见,我了解 ngReact,我只想知道使用 React 加速 Angular 的其他方法。

【问题讨论】:

  • 迟到总比不到好。。出于好奇,我不得不问,你为什么要同时使用 ReactJS 和 AngularJS?

标签: javascript angularjs angularjs-directive reactjs


【解决方案1】:

是的,这很好,它不会多次安装组件。

当你调用 React.renderComponent() 时,第二个参数是 react 应该渲染组件的元素。因此,如果您将相同的组件渲染到已经包含该组件的已挂载实例的 dom 元素,并且不重新挂载整个组件,它只是更新它的属性,则反应通知。

如果您创建一个定义了componentDidMount 函数的组件,您可以看到这一点。您会注意到 componentDidMount 只会在第一次调用 renderComponent 时执行。之后,在同一目标 dom 元素上对 renderComponent 的后续调用将不会调用它,因为该组件已经挂载。同样,getDefaultStategetDefaultProps 也只会在第一次调用 renderComponent 时被调用。

如果您要问,每次回答是肯定的时候都会调用组件的render 函数。但这就是 react 的工作原理,您希望调用 render 函数,因为 props 可能已更改。您可以通过使用shouldComponentUpdate (http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate) 并返回 false 来阻止它被调用。但是,react 开发人员建议您不要使用它来阻止渲染调用,除非您有特定的性能问题 - 大多数时候让渲染调用执行应该没问题,因为它不会导致任何缓慢的 dom 更新,除非事情确实发生了变化。

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2023-04-02
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多