2017-05-05 86 views
5

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

什么做

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

干脆把所有的构造函数外像

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

是一种选择优于其它以及是否有任何性能问题,我应该知道的区别?这一直在困扰着我,我似乎无法找到一个具体的答案。

+0

构造函数外的'foo = bar'语法*是无效的JavaScript,它是一个实验性功能。 –

回答

5

你的两个例子在功能上是完全相同的,但关键是在类方法之外分配东西,但在类的主体内部,就像你对renderconstructor以外的其他东西,不是标准的ES6,只能通过Babel工作。该语法是建议的class property syntax

+0

没错。我知道巴贝尔正在发挥它的魔力,但不太清楚这种折衷是什么(如果有的话)。另外我发现[这篇文章](https://medium.com/@joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a)有一些帮助。谢谢。 – user3802738