gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:08:07 25 4
gpt4 key购买 nike

我最近开始在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com