2022年前端React的100道面试题的第6题:Class组件挂载时生命周期

209 阅读1分钟

问题

React17的类组件被创建的生命周期顺序是?

选项

A static getDerivedStateFromProps() → constructor() → render() → componentDidMount()

B constructor() → render() → getSnapshotBeforeUpdate() → componentDidMount()

C constructor() → static getDerivedStateFromProps() → render() → componentDidMount()

D constructor() → render() → componentDidMount()

答案

C

解答

17.0 删除了生命周期方法 componentWillMount,修改为 UNSAFE_componentWillMount 别名,不再建议使用。

constructor()

constructor(props)

在 React 组件挂载之前,会调用它的构造函数。如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。

static getDerivedStateFromProps()

static getDerivedStateFromProps(props, state)

getDerivedStateFromProps 会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。

render()

render() 方法是 class 组件中唯一必须实现的方法。

注意:如果 shouldComponentUpdate() 返回 false,则不会调用 render()

componentDidMount()

componentDidMount() 会在组件挂载后(插入 DOM 树中)立即调用。依赖于 DOM 节点的初始化应该放在这里。

资料

组件的生命周期

UNSAFE_componentWillMount()

来源

搜索《考试竞技》微信小程序

gh_a246413495c8_258.jpg