React 组件加载模式(或反模式?)

React component loading pattern (or anti-pattern?)

我最近开始在我的 UI 项目中使用 ReactJS,这大大简化了我的 UI 工作流程。真的很愉快 API 一起工作。

我最近注意到我不得不在我的几个需要在页面上聚合数据的项目中使用一种模式。此数据将存在于 DOM 中,并且不依赖于使用 React 状态进行数据转换。

这是一个示例实现:

var Component = module.exports = React.createClass({

  componentDidMount: function() {
    this.component = new Component();
    this.component.start();
  },

  componentWillUnmount: function(prevProps, prevState) {
    if (this.component !== undefined) {
      this.component.destroy();
    }
  },

  render: function() {
    return (
      <div id="componentContainer"></div>
   );
  }

});


var Component = function(){
    // Some object that dynamically loads content in a 
    // pre-packaged NON-react component into componentContainer
    // such as a library that renders a graph, or a data loader 
    // that aggregates DOM elements using an infinite scroll
}

我的问题是这是否是使用 React 将数据聚合到 DOM 中的正确方法。我环顾四周寻找惯用的方法,但我的 google-foo 无法想出任何东西。

谢谢!

编辑 - 作为旁注,有人认为我使用 componentWillUnmount 销毁容器的方式会有问题吗?

主要问题是您使用的是 id,它不灵活并且对其余组件进行了假设(因为 id 必须是全局唯一的)。

module.exports = React.createClass({
  componentDidMount: function() {
    // pass a DOM node to the constructor instead of it using an id
    this.component = new Component(this.getDOMNode());
    this.component.start();
  },

  componentWillUnmount: function() {
    this.component.destroy();
  },

  render: function() {
    return <div />;
  }
});

您的 componentWillUnmount 没问题,但是您设置 this.component 的地方将始终 运行 在 componentWillUnmount 之前,没有其他原因它会是 assigned/deleted,所以 if 语句不需要。

此外,参数均未使用,也未提供给 componentWillUnmount。该签名属于 componentDidUpdate.