2017-09-27 76 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; 
}