React defining state without a constructor [duplicate]

醉酒当歌 提交于 2019-12-08 19:20:54

问题


I've seen some react developers define state without a constructor. I like the fact that is simplifies the code, but is it safe to do so?

class Dog extends React.Component {
   state = { sound: 'Woof' }
   return (
      <p>Dog says { this.state.sound }</p>
   )
}

I apologize in advance for the over simplified example.


回答1:


Its exactly the same thing. Take a look at the javascript that babel transpiles the code into. There is no difference.



来源:https://stackoverflow.com/questions/43546575/react-defining-state-without-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!