我正在使用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
中的代碼完成其執行時才執行?
你有一個語法錯誤,你的抓取文本只呈現。關閉網址末尾的引號。 –
謝謝,我已修復它。這只是一個構成錯誤。 –