2017-09-27 73 views
1

我正在調用異步函數,並且基於該響應,該函數應該返回不同的React本地元素。 我寫了更簡單的代碼,創建相同的錯誤。在異步函數之後不返回React Native元素

async function doNothing(){ }; 


class RouterComponent extends Component { 

    render() { 
     return(
      doNothing().then(()=> { 
       return(
        <View></View> 
       ); 
      }) 

我得到的錯誤是

一個有效的做出反應元素或(空)必須歸還。您可能返回了未定義的數組或其他無效對象。

我正在返回.then(statement)中的有效React元素。我將如何改變它,以便它返回React元素。

+2

如果我們在編寫代碼時考慮代碼,它將返回異步對象而不是有效的React元素。將異步操作移至其他生命週期方法(如componentDidMount)會更好。 – semuzaboi

+0

[我如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

回答

1

如果您想在同一個文件中執行異步操作,請將異步調用移動到某種生命週期方法,如ComponentDidMount。在構造函數中定義一個狀態對象,從你

constructor(props) { 
    super(props); 
    this.state = {ComponentToRender: ''} 
} 

觸發網絡呼叫componentDidMount方法,

componentDidMount() { 
    doNothing().then(()=> { 
    this.setState({ 
     ComponentToRender: <ComponentToRenderBasedOnResponse> 
    }) 
    }) 
} 

渲染方法應該使用this.state.ComponentToRender方法來決定,以渲染的成分。

render() { 
    if(this.state.ComponentToRender === 'A') { 
    return this.renderComponentA(); 
    } 
    else { 
    return null; 
    } 
} 

您可以決定,如何組織您的渲染方法。

0

在這種情況下渲染函數不是一個asncy函數。所以渲染功能不會等待你完成。所以它返回null。你可以嘗試這樣的事情。

constructor(props) { 
    super(props); 
    this.state = { renderA: false, renderB: false } 
} 

componentDidMount() { 
    doNothing().then((res)=> { 
    if (res.Something){ 
     this.setState({ renderA: true }) 
    } 
    }); 
} 

renderA() { 
    return (<View> view for A </View>); 
} 

renderB(){ 
    return (<View> view for B </View>); 
} 

render() { 
    this.state.renderA ? this.renderA() : null; 
    this.state.renderB ? this.renderB() : null; 
}