簡體   English   中英

如何訪問子組件中的父組件狀態?

[英]How to access parent component state in child component?

我在我的應用程序中使用react-router(v3)進行路由。 我有一些嵌套的路由,想訪問子組件中的父組件狀態。

路線:

<Route component={Main}>
   <Route path="home" component={Home} />
</Route>

主要成分(母體):

export default class Main extends Component {
  constructor(prop){
    super(prop);
    this.state = {
      user : {}
    }
  }

  render(){
    return (
      <div>
        Main component
      </div>
    )
  }
}

家庭組件(子組件):

export default class Home extends Component {
  constructor(prop){
    super(prop);
  }

  render(){
    return (
      <div>
        Main component
        want to access user data here. how to access user from parent component?
      </div>
    )
  }
}

Home組件中,我要訪問用戶數據,即在父組件Main 有什么方法可以訪問子組件中的父組件狀態?

您的問題是您不能僅將user作為道具傳遞給Home因為App不能直接渲染Home 您正在通過React-Router做到這一點。

您在這里有2種方法:

  1. 使用狀態管理解決方案(例如Reduxconnect() MainHomeconnect()到商店中的user 這樣, user不是Main狀態的一部分,而是應用商店的一部分,並且可以從其他組件進行訪問。 這是最復雜/可擴展的解決方案。
  2. 使用上下文 來自文檔: 在某些情況下,您希望通過組件樹傳遞數據,而不必在每個級別手動傳遞道具。 您可以使用功能強大的“上下文” API在React中直接執行此操作。 如果您想避免使用Redux或Mobx或任何狀態管理,則可以采用這種方法。

將父組件的狀態作為道具發送給子組件。 在Parent組件中像這樣獲取孩子...

<Home user={this.state.user} />

通過this.props.user訪問子級中的this.props.user

暫無
暫無

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

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