类组件
zh-hans.reactjs.org/docs/react-…
-
挂载阶段
- constructor()
- static getDerivedStatefromProps()
- render()
- componentDidMount()
-
更新阶段
- static getDerivedStatefromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
-
卸载阶段
- componentWillUnmount()
-
错误处理
- static getDerivedStateFromError()
- componentDidCatch()
-
其他API
- setState()
- forceUpdate()
-
class属性
- defaultProps
- displayName
-
实例属性
- props
- state
- React生命周期图示 projects.wojtekmaj.pl/react-lifec…
class DemoClass extends React.Component {
// 唯一修改state的地方
constructor(props) {
super(props)
// 私有属性:可变
this.state = {
counter: 100,
}
}
componentDidMount() {
// 在渲染过程中只执行一次。监听事件、获取DOM、请求数据等
}
shouldComponentUpdate(nextProps, nextState) {
return true
}
componentDidUpdate(prevProps, prevState, snapshot) {
// 判断参数是否变化,变化就调用请求函数重新请求数据
console.log(this.props === prevProps)
}
componentWillUnmount() {
// 清理定时器、取消网络请求、取消时间监听等
}
handleClick() {
this.setState((state, props) => ({
counter: state.counter + 1
}), () => {
// callback回调,可及时拿到已更改的state
})
}
render() {
return (
<div>
<p>{ this.state.counter }</p>
<Button onClick={ () => handleClick() }>按钮</Button>
</div>
)
}
}