![](/img/trans.png)
[英]What is the difference between using constructor vs state = {} to declare state in react component?
[英]React: What is the core difference between setting a state in a constructor vs. just setting the state within the class?
這里的核心區別是什么? 我以相似的方式成功地使用了這兩種方法。 但是,幕后正在發生什么,使它們與眾不同,何時應使用每種方法?
class Store extends React.Component {
constructor(props){
super(props)
this.state = {
checked: false
}
}
與
class Store extends React.Component {
state = { checked: false }
}
這兩種方法沒有“應該”。 您的第二個示例是一個新建議: class-fields 。 就是這個。 因此,如果您不需要使用constructor
,則可以跳過它並定義state
,如果需要則可以定義類方法,例如第二個示例。
您需要Babel和特定的插件才能使用此新建議。 由於您可以成功使用它,這意味着您已經有了此插件。 在后台,您的第二個代碼被編譯為如下所示:
class Store extends React.Component {
constructor(...args) {
var _temp;
return (_temp = super(...args)), (this.state = { checked: false }), _temp;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.