【问题标题】:setState cause Invariant Violation addComponentAsRefTosetState 导致 Invariant Violation addComponentAsRefTo
【发布时间】:2015-03-26 00:50:12
【问题描述】:

我将react-railsFluxxorReact 一起使用。只要我停留在同一页面上,我的组件就可以完全正常工作。

但是,如果我通过单击其他链接更改页面并返回到我的组件,当我尝试在其上使用 setState 时,它会抛出错误:

Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref.

我的实际代码可以在here 找到。问题似乎是setState 方法here。也许我的Chosen 组件的refs 属性不能重新渲染?可能是Turbolink引起的?

【问题讨论】:

    标签: javascript ruby-on-rails reactjs


    【解决方案1】:

    我认为这是Chosen组件的实现问题。

    当它被赋予新的道具时,React 会重新渲染它并将新节点放入页面中。然而,$.fn.chosen 已经被实例化了,它被附加到页面中不再存在的 DOM 节点上。我怀疑在此过程中的某个地方,对旧节点和组件的引用会被保留,即使在它们被卸载之后也是如此。

    我在使用 select2 和 React 时遇到了同样的问题。我发现 Ryan Florence 的 jQuery + React 指南非常有帮助:

    我们需要一种方法来停止使用 React 进行渲染,执行 jQuery 对话框工作,然后再次开始使用 React 进行渲染。有些人称这些为“门户”。你打开一个门户让 React 跳过一些老式 DOM 的东西,然后继续往下走。

    最大的技巧是什么都不渲染,然后在组件中调用 React.renderComponent。

    var Dialog = React.createClass({
      render: function() {
        // don't render anything, this is where we open the portal
        return <div/>;
      },
      componentDidMount: function() {
        var node = this.getDOMNode();    
        // do the old-school stuff
        var dialog = $(node).dialog().data('ui-dialog');
        // start a new React render tree with our node and the children
        // passed in from above, this is the other side of the portal.
        React.renderComponent(<div>{this.props.children}</div>, node):
      }
    });
    

    来源https://github.com/ryanflorence/react-training/blob/gh-pages/lessons/05-wrapping-dom-libs.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2015-01-21
      • 2021-01-29
      • 2018-12-08
      • 2018-03-26
      • 2021-06-04
      相关资源
      最近更新 更多