簡體   English   中英

如何使用父級(類組件)的上下文值更新子組件中的 state

[英]How to update state in child component with context value from parent (class components)

我知道如何使用功能組件來做到這一點(除非我弄錯了)。

const [childComponentStateVar, setChildComponentStateVar] = useState()

useEffect(() => {

    setChildComponentStateVar(context.newDataFromParent)

}, [context.newDataFromParent])

在此示例中,每次 context.newDataFromParent 更改時,state 都會更新。

但我不知道基於 class 的組件中的等價物,而且我無法在網上找到它。 有什么幫助嗎?

我的另一個問題是,這樣做有意義嗎?

  1. 在 class 組件中,您可以使用組件的componentWillReceiveProps生命周期 function 來完成。
class Component extends React.Components {
  componentWillReceiveProps = (nextProps) => {
    if (nextProps.data !== this.props.data) {
      this.props.setChildComponentStateVar(data)
    }
  }
  
  render() {
    return ( <div /> );
  }
}
  1. 沒有任何用例的上下文很難回答這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM