我目前正在編寫Android React Native應用程序,該應用程序由通過Ruby on Rails服務器提供的JSON API支持。我目前最大的困難是保存了fetch
電話的結果。我的代碼如下:使用React Native時,如何保存提取結果?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
Alert
} from 'react-native';
class MiniMinionClient extends Component {
constructor(props) {
super(props);
}
getStatus() {
return fetch('http://10.0.2.2:3000/api/v1/status.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
render() {
var status = this.getStatus()
return (
<View style={styles.container}>
<Text>Version {status.version}</Text>
<Text>Last Update: {status.last_update}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
AppRegistry.registerComponent('MiniMinionClient',() => MiniMinionClient);
我不知道這是一個有效的端點,因爲我能夠做同樣的工作隨叫隨到,如果我用警惕的帖子,我計上心來從here。我認爲這個問題源於fetch
的異步性質,但我不知道如何解決這個問題。
任何幫助將不勝感激!
你能提供'responseJson'的輸出還是json文件的數據?如果我知道格式,我可以爲您提供完整的工作代碼。 –
作爲函數結果返回的值是一個Promise對象,並且json文件的數據是 { 「version」:「0.0.1」, 「last_update」:「07/27/2016 at 06:15 AM「 } – Riizu