React 组件拥有对象

React component owning objects

是否推荐在 React 组件中拥有其他对象?这样做有什么缺点吗?我看到它完成了

这是我的例子:

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>
        );
    }
}

效用是 class 为组件提供更多功能。我检查过的大多数例子都没有这种东西。如果可以使用那么在构造函数中实例化还是在挂载函数中实例化会更好?

没关系。我更愿意在构造函数中执行此操作,因为我觉得这更像是一个初始化过程。 React 生命周期方法相互通信的唯一方法是在状态(或道具)或 this 变量中查找。

大多数情况下,将随机事物置于状态中只会通过一次又一次地调用渲染来导致性能问题,因此您应该尝试将这些变量移动到这样的状态:

this.utility = new Utility();

此外,如果这是在多个地方使用的东西,请考虑将其传递给父项的道具。这样你就可以在子组件的任何地方使用相同的初始化对象(但这取决于你的用例)。

既然是实用工具,建议使用单例设计模式.

的确,我花了将近 6 个月的时间像您的代码片段一样工作。

但是,我现在切换到 单例设计模式,如下所示:

Utility.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>
        );
    }
}