【问题标题】:React component owning objectsReact 组件拥有对象
【发布时间】:2017-02-18 19:02:29
【问题描述】:

是否建议在 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>
        );
    }
}

Utility 是为组件提供更多功能的类。我检查过的大多数示例都没有这种东西。如果可以用的话,是在构造函数中实例化还是在挂载函数中实例化更好?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 es6-class


    【解决方案1】:

    既然是实用工具,推荐使用单例设计模式

    确实,我花了将近 6 个月的时间来工作,就像你的 sn-p 节目一样。

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

    实用程序.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>
            );
        }
    }
    

    【讨论】:

    • 好点!在我现在工作的一种情况下会有意义。
    • 欢迎@Janne .. 顺便说一句,以下所有?? constructor(props) { super(props); this.utility = new Utility(); } 都可以替换为 utility = new Utility(); 。它与我的答案无关,但与 ES7 有关,因为您已经在类中使用static 属性。
    • 在我的项目中尝试过单例方法,它是两个实用程序类的完美解决方案?
    • 恭喜! ???
    【解决方案2】:

    没关系。我更喜欢在构造函数中执行它,因为我觉得这更像是一个初始化过程。 react 生命周期方法相互通信的唯一方法是在 state(或 props)或 this 变量中查找。

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

    this.utility = new Utility();
    

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

    【讨论】:

    • 我猜 React 应用程序的设计变得更加重要,只是为了避免不必要的 props 臃肿,同时将仍然重要的 props 传递到正确的位置。
    • 这真的取决于用例
    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2018-11-29
    • 2015-11-16
    • 2016-06-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多