React + Backbone,目标容器不是DOM元素

IT技术 javascript backbone.js reactjs
2021-05-22 15:56:04

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

所以我正在尝试一个实验,我从基于该页面的骨干路由器渲染一个 post 组件。现在我知道你通常不会这样做,事情会变得混乱等等。但同样这只是一个实验

所以我在主干中有以下路由(注意react调用):

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.

这是因为我试图呈现组件的方式吗?

2个回答

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

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

或者

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

那么您将拥有对实际 DOM 节点的引用。

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

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

将 React 组件渲染到提供的容器中的 DOM 中,并返回对该组件的引用。

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