简体   繁体   中英

React component loading pattern (or anti-pattern?)

I've recently started using ReactJS in my UI projects which has greatly simplified my UI workflow. Really enjoyable API to work with.

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.

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. I looked around for the idiomatic way of doing this, but my google-foo was unable to come up with anything.

Thanks!

EDIT - as a side note, does anyone think there will be a problem with the way I destroy the container, using the 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).

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.

Also the arguments both weren't used, and aren't provided to componentWillUnmount. That signature belongs to componentDidUpdate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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