React Learning

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 add super(), it is for initializing this, and can bind events to this.
  • super(props):
    If you want to use this.props in a constructor, also need to add super(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
2
3
4
5
6
7
8
9
10
11
12
class Sample extends React.Component {
constructor(props) {
super(props);
this.props.attr1 = "a1";
this.props.attr2 = "a2";
this.state = {
some: "Sample's value",
arr: [],
opt: "c"
}
}
}

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
2
3
4
5
6
class App extends React.Component{
state = {
data: {}
}
// ...
}

It works equal to

1
2
3
4
5
6
7
8
9
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
data: {}
}
}
// ...
}

React hooks

4 basic hooks: http://www.ruanyifeng.com/blog/2019/09/react-hooks.html
useState, useContext, useReducer, useEffect

Updated 2020 (focus on useEffect()): http://www.ruanyifeng.com/blog/2020/09/react-hooks-useeffect-tutorial.html