簡體   English   中英

使用從父組件中進行的異步 api 調用接收的道具更新反應子組件的狀態

[英]update react child component's state using props received from an async api call made in the parent component

我想要做的是使用 props 設置我的狀態,但問題是我的 props 來自父組件中的 api 調用(我使用的是 react router dom)。 因此,首先我嘗試使用 componentDidMount,它在您從歡迎頁面(child)進入 Home(Child)時起作用,但是當您直接進入主頁時,組件確實在進行 api 調用之前填充了狀態(因此基本上未定義)。

接下來我嘗試使用 componentDidUpdate 當你直接進入 Home(child) 時它可以工作,但是當你從歡迎頁面(child) 進入 Home(child) 時 componentDidUpdate 甚至不會觸發。(所以再次未定義)(componentdidupdate 不運行時組件已初始化,即第一次制作組件)如果您導航到另一條路線並返回它在 componentDidUpdate 的情況下不起作用我認為組件生命周期從一開始就開始有人可以確認這一點嗎?

現在我在我的代碼中同時使用 componentDidUpdate 和 componentDidMount 並且它運行良好。 我只想知道這是最好的方法還是有另一種方法來使用來自 api 調用的道具填充狀態

主頁組件

constructor(props: HomeProps) {
    super(props);
    this.state = {
      myUser: {},
    }
  }


  componentDidUpdate = (prevProps: HomeProps) => {
    if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
      this.setState({ myUser: this.props.userProfile });
    }
  }

componentDidMount = () => {
    this.setState({ myUser: this.props.userProfile })
  }

主要組件(父)歡迎:路徑=“/”主頁:路徑=“/主頁”

<HashRouter>
<Switch>
    <Route exact path="/" render={(props) => (<Welcome {...props} />)} />
                   <Route exact path="/Home" render={(props) => (<Home authContext={this.props.authContext} {...props} userProfile={this.state.currentUser} />)} />
</Switch>
</HashRouter>

只是想知道正確的方法,如果你能解釋為什么它更好,我也會很感激。

我的結構方式不是將不同的路由作為父 - 子,而是將它們視為平行或兄弟姐妹。 在那種情況下,我會使用 Redux 或您首選的狀態管理。 隨着您的應用程序的增長和您添加更多路由,您必須將用戶道具從您的父路由傳遞到所有未來的路由,並且維護起來將是一個更大的問題。

通過使用像 Redux 這樣的狀態管理工具,所有組件都可以訪問狀態,無論路由走多深或添加多少兄弟路由,都無需將 props 傳遞給每個組件。

首先你應該使用 async/await api 調用,如果你在 api 中使用 async/await 本身就可以解決這個問題,你可以像下面這樣使用。

   constructor(props: HomeProps) {
        super(props);
        this.state = {
          myUser: {},
        }
      }        
      componentDidUpdate = async(prevProps: HomeProps) => {
        if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
        await  this.setState({ myUser: this.props.userProfile });
        }
      }        
   componentDidMount = async () => {
       await this.setState({ myUser: this.props.userProfile })
      }

暫無
暫無

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

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