react 生命周期
生命周期
- 每个生命周期钩子的调用例子讲解的比较详细
生命周期钩子的函数
React 的生命周期包括三个阶段:mount(挂载)、update(更新)和 unmount(移除)
mount 阶段
constructor() - 初始化 props 和 state
componentWillMount() - 将要挂载了!
render() - 将 return 里的内容挂载到页面中
componentDidMount() - 挂在完了要干点什么?
update 阶段
componentWillReceiveProps(nextProps) - 我要读取 props 啦!
shouldComponentUpdate(nextProps, nextState) - 请问要不要更新组件?true / false
componentWillUpdate() - 我要更新组件啦!
render() - 更新!
componentDidUpdate() - 更新完毕啦!
unmount 阶段
componentWillUnmount() - 我要死啦!
setState 应该放在哪?
一般,我们只在这几个钩子里 setState:
componentWillMount - 一个组件只执行一次
componentDidMount - 一个组件只执行一次
componentWillReceiveProps - 每次数据更新时执行一次
因为在 componentWillUpdate 和 componentDidUpdate 里 setState 后
又会触发这两个钩子,最终会导致 call stack 溢出
许可协议: "署名-非商用-相同方式共享 4.0"
本文链接:http://ldq-first.github.io/2017/09/26/React-生命周期/