TIL_180712 ReactJS Component (cycle, smart/dumb)

ReactJS

Order in component cycle

  1. componentWillMount(): request api
  2. render()
  3. componentDidMount()

Update stage

  1. componentWillReceiveProps() -
  2. shouldComponentUpdate(): comparison in new prop and old prop, if have changes, == true
  3. componenetWillUpdate()
  4. render()
  5. componentDidUpdate()

Data type checking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Movie extends component{
static propTypes = {
//isRequired = 'Movie' has to have a title(string) as a prop
title: PropTypes.string.isRequired,
poster: PropTypes.string
}
render(){
return(
<div>
<MoviePoster poster={this.props.poster}/>
<h1> {this.props.title}</h1>
</div>);
}
}

State

  • state = {}
  • if ‘state’ change, component do ‘render()’ again automatically
  • when want to change the state’s value, should use this.setState({content})
  • can’t over ride like ‘this.state.varName = ‘other value’ -> automatic change ain’t be happend.
  • TIP for infinite scroll

Smart Componenet vs Dumb Componenet

  • if component doesn’t need to have componenetWillMount, function, updateState, render but only do ‘return’, it can be stateless componenet (= Dumb Componenet).
  • use ‘functional component’ instead of ‘class componenet’
  • for checking prop type: use the name instead of ‘static’ keyworkd.
  • eg) MoviePoster.proptypes = { poster: PropTypes.string.isRequired}

How to change smart component into dumb.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// before
class MoviePoster extends Component{
render(){
return(
<img src={this.props.poster}/>
);
}
}
// after = dumb componenet
function MoviePoster({poster}){
return(
<img src={poster} />
)
}