我正在从我的react-native代码进行GET请求调用,而GET请求的响应如下所示-
[
{
"id": 1,
"title": "homework",
"detail": "nothing details",
"status": "1",
"url": "www.google.com",
"mail": "a@a.com",
"phone": "0171551223366",
"category": "2",
"timestamp": 12.3
},
{
"id": 2,
"title": "homework",
"detail": "nothing details",
"status": "1",
"url": "www.google.com",
"mail": "a@a.com",
"phone": "0171551223366",
"category": "2",
"timestamp": 12.3
}
]
如果这是一个简单的json响应,则解析完全没有问题,但是如果这是一个数组,那么我将无法获取和保存它们。
我在这里给出了我的代码-
import React from 'react';
import { StyleSheet, Text, View, Image, AsyncStorage, ActivityIndicator } from 'react-native';
import {Icon, Button, Container, Header, Content, Left} from 'native-base';
import CustomHeader from './CustomHeader';
let jwt=''
class NoteMeHome extends React.Component {
state = {
getValue: '',
dataSource:[],
isLoading: true
}
componentDidMount() {
AsyncStorage.getItem("token").then(value => {
console.log(value);
jwt = value;
this.setState({
getValue: value,
});
});
const url = 'my url';
fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'abcd',
'jwt': jwt
})
})
.then((response)=> response.json() )
.then((responseJson) => {
console.log('####:'+responseJson.title)
this.setState({
dataSource: responseJson,
isLoading: false
})
})
.catch((Error) => {
console.log(Error)
})
}
static navigationOptions = ({navigation}) => ({
title: "Home",
headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
onPress={()=>navigation.navigate('DrawerOpen')}/>,
drawerIcon:
<Image source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}
style={styles.icon}
/>
})
render() {
const { getValue } = this.state;
return(
this.state.isLoading
?
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<ActivityIndicator size="large" color="#330066" animating/>
</View>
:
<Container>
<CustomHeader
title="Home"
drawerOpen={()=>this.props.navigation.navigate('DrawerOpen')}
/>
<Content contentContainerStyle={{flex:1, alignItems:'center',
justifyContent:'center', padding:10}}>
<Button full onPress={()=> this.props.navigation.navigate('Settings')}>
<Text style={{color:'white'}}>Go To Settings</Text>
</Button>
<Text>{this.state.getValue}</Text>
</Content>
</Container>
)
}
}
const styles = StyleSheet.create({
icon:{
height: 24,
width: 24
}
})
export default NoteMeHome;
因此,如果有人帮助我处理这段代码并提出如何将数据从json响应中保存到数组中,那将非常好。
答案 0 :(得分:1)
它应该可以工作。否则,您可以这样做
for (var i = 0; i < responseJson.length; i++){
this.state.dataSource.push({
...
})
}