首页 > 解决方案 > 挂载上的 ReactJS 方法

问题描述

最近我进行了一次在线测试,其中提出了以下问题:

挂载 React 组件时不执行以下哪个方法?

  1. 构造函数()
  2. 使成为()
  3. 组件WillReceiveProps()
  4. 组件DidMount()

我相信所有这些方法都会在安装 React 组件时执行。但是我确实选择了选项 4.componentDidMount(),即使它是错误的,因为我必须选择一个选项,是的,在线测试说它是错误的。 根据 Pluralsight 上的一篇文章,上述所有方法都将在挂载时执行(不推荐使用 componentWillReceiveProps(),应使用静态 getDerivedStateFromProps())。

我不明白的是

  1. 问错了吗?
  2. 选项错了吗?
  3. 我对问题的理解是错误的?

我很困惑。请帮助我获得正确的观点。

提前致谢。

标签: reactjs

解决方案


The documentation for componentWillReceiveProps says

is invoked before a mounted component receives new props.

It operates on a already mounted component receiving new props. A component being mounted cannot receive new props until it has initial props.

Also note that getDerivedStateFromProps is not a 1 for 1 replacement method. It is suggested as an alternative for operations that were typically done in componentWillReceiveProps, but they do not do the same thing.


推荐阅读