React 是 Facebook 开发的 declarative UI toolkit.
Tips
Component Lifecycle
Single Component
单个 Component 的生命周期:(按顺序)
创建(Mounting)
这里的所有阶段仅在 Component 初始化时发生一次。
- constructor()
- componentWillMount() (deprecated)
- static getDerivedStateFromProps()
- render()
- componentDidMount()
- constructor 里直接用 this.state = {},而不使用 this.setState
- render 应该是 pure 函数,不应该在里面调用 this.setState 或造成任何副作用。
- Server Side Render 仅执行上表里 1-4 阶段,不会执行 componentDidMount。
更新(Updating)
这里的阶段会重复发生。只有客户端会执行这里的阶段,Server Side Render 没有 Updating 部分。
- componentWillReceiveProps() (deprecated)
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- componentWillUpdate() (deprecated)
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
Components Composition
假设 JSX 结构:
<Parent>
<Child /> // Child 1
<Child /> // Child 2
</Parent>
则该部分组件生命周期为:
1. <Parent> componentWillMount()
2. <Parent> render(), which starts to render children
3. <Child> 1 componentWillMount()
4. <Child> 1 render() of the first child
5. <Child> 2 componentWillMount()
6. <Child> 2 render()
7. <Child> 1 componentDidMount() (these will start only after the last render in the tree has run)
8. <Child> 2 componentDidMount()
9. <Parent> componentDidMount() (this one will run only after its last child has run componentDidMount)
但对于 Server Side Render,只有 componentWillMount 和 render 会被执行,即上面列表里的 1-6 阶段。