2017-04-10 31 views
0

我正在使用React Native 0.43。我有一個組件,名爲ApiComponent。在這個組件的componentWillMount方法中,我從API中獲取一些結果,並且我想在我的render方法中得到這個結果。我在我的組件使用下面的代碼(刪節版):反應:如何確保在其他人之前完成某些生命週期方法

export default class ApiComponent extends Component { 

    constructor(props) { 
    super(props); 

    this.state = { 
     statement: {}, 
    }; 
    } 

    componentWillMount() { 
    fetch('http://example.com/api_url/') 
    .then(response => response.json()) 
    .then(data => this.setState({ statement: data })) 
    .catch(error => console.error(error)); 
    } 

    render() { 
    return (
     <Text>{'Rendering API: ' + console.log(this.state.statement)}</Text> 
    ); 
    } 
} 

現在,當我運行此代碼,我得到一個空的結果在我的控制檯Rendering API: {}。根據我的理解,render方法在從API返回結果之前執行,因此狀態不會被結果更新。

我的問題是,我如何確保我的render方法僅在我的componentWillMount中的代碼完成其執行時才執行?

+0

你有一個語法錯誤,你的抓取文本只呈現。關閉網址末尾的引號。 –

+0

謝謝,我已修復它。這只是一個構成錯誤。 –

回答

1

您可以使用一個三元操作,以確保如果this.state.statement是真的

return (
    { this.state.statement ? <Text>{'Rendering API: ' + console.log(this.state.statement)}</Text> : null } 
) 
+0

我需要在我的'render'方法中使用API​​的結果。它只會被渲染一次,並且'componentWillMount'方法更新它不會再次渲染的狀態。 –

相關問題