【问题标题】:React + Backbone, Target container is not a DOM elementReact + Backbone,目标容器不是 DOM 元素
【发布时间】:2014-07-19 10:09:54
【问题描述】:

注意:这是一个被抛出的反应错误。

所以我正在尝试一个实验,我根据该页面从骨干路由器渲染一个帖子组件。现在我知道您通常不会以这种方式做事,事情会变得混乱等等。但是再次这只是一个实验

所以我在主干中有以下路线(注意反应调用):

AisisWriter.Routers.Posts = Backbone.Router.extend({

  writer_posts: null,

  posts: null,

  mountNode: $('#blog-manage'),

  routes : {
      '': 'index'
  },

  initialize: function() {
    this.writer_posts = new AisisWriter.Collections.Posts();
  },

  index: function() {
    var options = { reset: true };
    this.writer_posts.fetch(options).then(this.postsRecieved, this.serverError);
  },

  // Deal with the posts received
  postsRecieved: function(collection, response, options) {
    this.posts = collection;

    // Walk through the posts.
    $.each(this.posts, function(key, value){
      // value is an array of objects.
      $.each(value, function(index, post_object){
        React.renderComponent(new Post({post: post_object}), this.mountNode);
      });
    });
  },

  // Deal with any server errors
  serverError: function() {
    console.log('There was an error trying to fetch the posts.');
  }

});

这个想法是它应该在页面上吐出一个帖子标题,一个接一个(我感觉它只会做一次)。

但问题是控制台说:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

这是因为我尝试渲染组件的方式吗?

【问题讨论】:

    标签: javascript backbone.js reactjs


    【解决方案1】:

    您将this.mountNode 设置为$('#blog-manage'),这是一个jQuery 对象(本质上是一个节点数组)。如果你改为这样做

    mountNode: $('#blog-manage')[0]
    

    mountNode: $('#blog-manage').get(0)
    

    然后您将参考实际的 DOM 节点。

    【讨论】:

    • 这是主干源的作用。它看起来 jenky/hacky,但我想这就是它的工作原理。
    【解决方案2】:

    React.renderComponent 将组件渲染为真实的 DOM 元素。抛出异常是因为您没有将 DOM 元素作为所需的第二个参数传递。

    ReactComponent renderComponent(
      ReactComponent component,
      DOMElement container,
      [function callback]
    )
    

    在提供的 DOM 中渲染一个 React 组件 容器并返回对组件的引用。

    如果你只想要 React 的 HTML,你可以使用 React.renderComponentToStaticMarkup 代替。

    【讨论】:

    • 所以我更新了我帖子中的代码,给它一个节点——它确实存在,但我不确定我是否做对了,因为错误是一样的......
    • this 不是您在循环中所期望的。您需要设置$.each 调用的上下文:$.each(function() { ... }, this);
    猜你喜欢
    • 2017-02-20
    • 2014-12-12
    • 1970-01-01
    • 2019-01-13
    • 2018-11-21
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多