React中的构造方法

use*_*738 5 javascript ecmascript-6 reactjs

我已经阅读了关于构造函数方法的React Docs以及它可以用于设置状态和绑定函数的内容,但在大多数情况下它是否真的有必要?

这样做有什么区别

export default class MyClass extends Component {
    constructor(props) {
        super(props);
        this.state = {
            foo: 'bar',
        };
        this.member = 'member';
        this.someFunction = this.anotherFunction(num);
    }
    anotherFunction = (num) => num * 2;
    render() {
        // render jsx here
    }
}
Run Code Online (Sandbox Code Playgroud)

并简单地把所有的东西放在构造函数之外

export default class MyClass extends Component {
    state = {
        foo: 'bar',
    };
    member = 'member';
    someFunction = this.anotherFunction(num);
    anotherFunction = (num) => num * 2;
    render() {
        // render jsx here
    }
}
Run Code Online (Sandbox Code Playgroud)

一种选择是否优先于另一种选择,是否存在我应该了解的任何性能问题?这一直困扰着我,我似乎无法找到具体的答案.

log*_*yth 5

你的两个例子在功能上是相同的,但关键是在类方法之外分配东西,但是在类的主体内部,就像你拥有除了render和之外的所有东西一样constructor,不是标准的ES6,并且只能通过Babel工作.该语法是建议的类属性语法.