简体   繁体   English

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

[英]React component loading pattern (or anti-pattern?)

I've recently started using ReactJS in my UI projects which has greatly simplified my UI workflow. 我最近开始在UI项目中使用ReactJS,这大大简化了UI工作流程。 Really enjoyable API to work with. 真正令人愉快的API。

I've noticed recently that I've had to use a pattern in a couple of my projects that needed to aggregate data on a page. 我最近注意到,我不得不在一些需要在页面上聚合数据的项目中使用一种模式。 This data would live in the DOM and not be dependent on using the React state for data transitions. 这些数据将存在于DOM中,而不依赖于使用React状态进行数据转换。

This is an example implementation: 这是一个示例实现:

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
}

My question is whether or not this is the proper way to aggregate data into the DOM using React. 我的问题是这是否是使用React将数据聚合到DOM中的正确方法。 I looked around for the idiomatic way of doing this, but my google-foo was unable to come up with anything. 我到处寻找惯用的方法,但是我的google-foo无法提出任何建议。

Thanks! 谢谢!

EDIT - as a side note, does anyone think there will be a problem with the way I destroy the container, using the componentWillUnmount? 编辑-作为附带说明,有人认为使用componentWillUnmount销毁容器的方式会有问题吗?

The main problem is that you're using an id, which is inflexible and makes assumptions about the rest of the components (because ids must be globally unique). 主要问题是您使用的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 />;
  }
});

Your componentWillUnmount was fine, but the one place you set this.component will always run before componentWillUnmount, and there's no other reason it'd be assigned/deleted, so the if statement isn't needed. 您的componentWillUnmount很好,但是您在其中设置了this.component的位置将始终在componentWillUnmount之前运行,并且没有其他原因将其分配/删除,因此不需要if语句。

Also the arguments both weren't used, and aren't provided to componentWillUnmount. 同样,两个参数均未使用,也未提供给componentWillUnmount。 That signature belongs to componentDidUpdate . 该签名属于componentDidUpdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM