2017-05-08 12 views
2

我有一個反應應用程序,我想異步獲取一些數據,處理它,更改當前組件狀態,然後將它作爲道具傳遞給渲染中的另一個組件。我試圖在componentWillMount中獲取它,但好像在數據被提取之前渲染仍然發生。什麼是工作解決方案?我也嘗試在ES6構造器中獲取數據,並且問題仍然存在。如何在組件內異步獲取數據並將其作爲道具傳遞給渲染中的另一個組件?

任何幫助,非常感謝!

回答

4

那麼獲取數據的理想場所是componentWillMount函數,然而由於異構性,您的子組件在獲取數據之前可能會呈現,因此您可以執行兩項操作。

保持加載狀態下,不渲染,直到返回的組件是牽強,像:

constructor() { 
    super(); 
    this.state = { 
     isLoading: true, 
     // other states 
    } 
} 

componentWillMount() { 
    //your async request here 
} 

render() { 
    if(this.state.isLoading) { 
     return null; // or you can render laoding spinner here 
    } else { 
     return (
      //JSX here with the props 
     ) 
    } 
} 

另一種方法是有一個空的道具,並在子組件的檢查執行:

constructor() { 
    super(); 
    this.state = { 
     someProps: null; 
    } 
} 

componentWillMount() { 
    //your async request here 
} 

render() { 

    return (
     <Child someProps={this.state.someProps}/> 
    )  
} 

兒童

render() { 

    if(this.props.someProps == null) 
     return null; 
    else { 
     return (//JSX contents here); 
    } 
} 
+0

我個人比較喜歡第一種方法 –

+0

非常感謝!這非常有幫助!它的工作:) – code83

+0

由於某種原因,我的單元測試現在雖然失敗。呈現沒有崩潰的對象的基本測試失敗。它與上述解決方案有什麼關係,我該如何解決這些問題? – code83

相關問題