这个问题在这里已有答案:
- What is the difference between using constructor vs state = {} to declare state in react component? 2个答案
我见过两者
export default class LoginScreen extends React.Component {
constructor(props){
super(props);
this.state = {
loading: false,
loggedIn: false,
}
}
}
和
export default class LoginScreen extends React.Component {
state = {
loading: false,
loggedIn: false,
}
}
两者的用例有哪些?有优点/缺点吗?这是一个更好的做法吗?
2 回答
Use constructor when you want to save props data into state
Otherwise you can directly set the state for hard coded data
两种情况下的表现相同,所以这只是个人偏好的问题 . 在类之外定义状态恰好比在构造函数中定义它更新的实现,所以我建议你使用显式状态定义 .