是否建议在 React 组件中拥有其他对象?这样做有什么缺点吗?我看到它已经完成了here
这是我的例子:
import React, {Component} from 'react';
import Utility from './Utility';
export default class MyComponent extends Component {
static defaultProps = {
message: 'Hello',
name: 'John!'
};
constructor(props) {
super(props);
this.utility = new Utility();
}
render() {
return (
<h1>{this.props.message}, {this.props.name} {this.utility.getText()}</h1>
);
}
}
实用程序是为组件提供更多功能的类。我检查过的大多数示例都没有此类内容。如果好用的话是在构造函数中实例化好还是在挂载函数中实例化好?
最佳答案
由于它是一个实用程序,因此建议使用单例设计模式。
事实上,我花了将近 6 个月的时间,就像你的代码片段所示那样工作。
但是,我现在切换到单例设计模式,如下所示:
实用程序.js
class Utility {
// methods
}
export const utility = new Utility();
export default Utility; //👈🏼 i know, you are using only this .. use also the above 👆 to export the singleton
然后,在你的 React 组件中:
import React, {Component} from 'react';
import {utility} from './Utility'; //👈🏼 import with "{utility}" not "Utility"
export default class MyComponent extends Component {
static defaultProps = {
message: 'Hello',
name: 'John!'
};
constructor(props) {
super(props);
// this.utility = new Utility(); <-- no need 🔇
}
render() {
return (
<h1>{this.props.message}, {this.props.name} {utility.getText()}</h1>
);
}
}
关于javascript - React 组件拥有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42319418/