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

标签 javascript reactjs

我最近开始在我的 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 之前运行,并且没有其他原因它会被分配/删除,所以不需要 if 语句。

此外,这些参数都没有被使用,也没有提供给 componentWillUnmount。该签名属于 componentDidUpdate .

关于javascript - React 组件加载模式(或反模式?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747684/

相关文章:

javascript - 使用 onLoad 事件提高前端性能

c# - 通过数组作为 $ajax 参数 MVC

reactjs - Redux 坚持重新水化先前的身份验证状态为时已晚

javascript - MouseMove 事件上 React 组件内 Canvas 上的矩形选择

reactjs - 如何在事先不知道设备屏幕尺寸的情况下为响应式应用程序执行 SSR?

javascript - 我的 meteor 路由有什么问题吗?

c# - 将 MVC 操作结果发送到打印机

javascript - 命名函数是 jsx Prop 的好习惯吗?

reactjs - 如何获取 react 元素的宽度

javascript - cakephp 2.4 中的自动完成实现