javascript - React 组件拥有对象

标签 javascript reactjs ecmascript-6 es6-class

是否建议在 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/

相关文章:

javascript - 如何在除具有给定 ID 的一个文本区域之外的所有文本区域上启用 nicEdit?

javascript - 添加和删​​除类数组错误

javascript - 通过映射函数 react 更改记录属性无法正常工作

javascript - ES6类的proto继承

javascript - 将流类型应用于常量函数

javascript - Javascript 可以访问 Ajax 文本/html 响应的 DOM 吗?

javascript - 使用 jquery 显示时如何将 <a> 标签的名称传递给 <div> 标签?

javascript - ReactJS 属性验证

javascript - 如何仅在存在时才需要模块。 react native

javascript - jQuery 将十六进制转换为 rgba