【问题标题】:How to update state in child component with context value from parent (class components)如何使用来自父(类组件)的上下文值更新子组件中的状态
【发布时间】:2021-07-31 10:03:50
【问题描述】:

我知道如何使用功能组件(除非我弄错了)。

const [childComponentStateVar, setChildComponentStateVar] = useState()

useEffect(() => {

    setChildComponentStateVar(context.newDataFromParent)

}, [context.newDataFromParent])

在此示例中,每次 context.newDataFromParent 更改时,状态都会更新。

但我不知道基于类的组件中的等价物,而且我无法在网上找到它。有什么帮助吗?

我的另一个问题是,这样做有意义吗?

【问题讨论】:

  • 示例中有问题const [a, setA] = useEffect() 你的意思是useState
  • 是的 useState,为此道歉。

标签: javascript reactjs react-hooks components


【解决方案1】:
  1. 在类组件中,可以通过组件的componentWillReceiveProps生命周期函数来实现。
class Component extends React.Components {
  componentWillReceiveProps = (nextProps) => {
    if (nextProps.data !== this.props.data) {
      this.props.setChildComponentStateVar(data)
    }
  }
  
  render() {
    return ( <div /> );
  }
}
  1. 如果没有您的用例背景,很难回答这个问题

【讨论】:

  • 我很感激,所以我看到你在这个中使用了道具。但是对于上下文更新,它是否同样有效?
  • 我不需要使用 setState,因为我想在孩子中设置状态吗?
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2018-04-20
  • 1970-01-01
  • 2023-02-19
  • 2019-06-03
  • 2021-07-04
相关资源
最近更新 更多