This is a recording of my study on React framework
super(props) | super() | no super
- super():
If constructor is used, there is a must to addsuper()
, it is for initializingthis
, and can bind events tothis
. - super(props):
If you want to usethis.props
in a constructor, also need to addsuper(props)
.
(No matter there is a constructor,this.props
can work in render(), this is auto-implemented by React) - no super:
If there is no constructor, super is not mandatory, cuz React will add a empty constructor as default.
Here I created a component using ES6 class:
1 | class Sample extends React.Component { |
The child class “Sample” must use a super()
to inherit the properties from parent class React.Component
.
For the above sample, the child class also want to declare new properties based on the inherits, so it needs to use super(props)
.
If only the state
is needed, super()
is enough.
This is because, this.props
must be an object, so we can declare properties under it.
But constructor(props){}
defined props
as an object.
What super(props)
does is to assign an object to props
(this.props=props
) in parent constructor, others with no passing parameters are assigned as undefined.
As there is no property under state
, it is ok to define state with super()
.
ref: https://www.cnblogs.com/itgezhu/p/11199313.html
skip constructor when using state
In ES7, it is supported to use state
only instead of build a constructor first.
1 | class App extends React.Component{ |
It works equal to
1 | class App extends React.Component{ |
React hooks
4 basic hooks: http://www.ruanyifeng.com/blog/2019/09/react-hooks.htmluseState
, useContext
, useReducer
, useEffect
Updated 2020 (focus on useEffect()
): http://www.ruanyifeng.com/blog/2020/09/react-hooks-useeffect-tutorial.html