Life cycle process:
1. Enter the initial rendering display for the first time: render()
- constructor(): Create an object to initialize the state
- componentWillMount(): callback will be inserted
- render(): Used to insert virtual DOM callback
- componentDidMount(): The callback has been inserted
2.Update state every time: this.setState()
- componentWilIUpdate(): The callback will be updated
- render(): update (re-render)
- componentDidUpdate(): The callback has been updated
3. Remove components
- ReactDOM.unmountComponentAtNode(document.getElementById(‘example’))
- componentWillUnmount() component will be removed callback
chestnut:
/*
需求: 自定义组件
1. 让指定的文本做显示/隐藏的动画
2. 切换时间为2S
3. 点击按钮从界面中移除组件界面
*/
class Animation extends React.Component{
constructor(props){
super(props)
this.state = {
opacity: 1
}
}
componentDidMount(){
let {
opacity} = this.state
setInterval(() => {
if(opacity*10 >0){
opacity -= 0.1
} else {
opacity = 1
}
this.setState({
opacity})
}, 500)
}
render(){
let opacity = this.state.opacity
return(
<div style={
{
opacity}}>
gogoogogogogogogogog
</div>
)
}
}
ReactDOM.render(<Animation/>, document.getElementById('example'))
Diff algorithm
Minimize the page redraw
. Compare the changed part before and after the change. The part that is compared will be rendered, and the other parts that have not changed will not be rendered.
There is a problem in this case
This can’t be written like before and will report an error <a href="javascript:;"
. It must be written like this in React.
Don’t forget, here prop is passed by value, it’s not a deconstructed assignment, just write the name.