componentWillReceiveProps / getDerivedStateFromProps

问题描述

我只是在学习React,遇到了我在任何地方都找不到的解释。

在我读过的有关React组件的每本书/博客中,我都看到一条类似的声明,即组件props是不可变的。更改组件属性的唯一方法是重新创建它。但是,事实似乎并非如此。

在阅读“反应迅速”和“快速反应”时,我遇到了对componentWillReceiveProps的引用,并解释了在props(不是状态)用于被改变。我已经看过有关此文档的文档(以及更新的getDerivedStateFromProps函数)。

componentWillReceiveProps的文档指出:

componentWillReceiveProps() is invoked before a mounted component receives new props. 

getDerivedStateFromProps的文档说明:

This method exists for rare use cases where the state depends on changes in props over time. 

这两个都不能解释在组件使用期内随时可以接收(更改)不可变的道具的情况。

那么,这里到底发生了什么?如果道具无法更改,这些功能/方法是做什么的?还是,这些书籍/博客被误认为是真的不是一成不变的?

解决方法

可以使用新的/更新的/不同的道具重新渲染组件。考虑以下组件:

function Parent () {
    const [count,setCount] = useState(0);

    setInterval(() => setCount(count + 1),1000);

    return (
      <CounterDisplay count={count} />
    )
}

CounterDisplay组件将每秒使用新的count道具重新渲染一次。如果CounterDisplay需要在重新渲染之前对新道具做出响应,则可以实现componentWillReceiveProps

实际上,这在运行最新版本的React的项目中很少见。多年以来,我还没有在React组件中实现componentWillReceiveProps方法。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...