我正在尝试制作一个显示从特定火车站到另一个火车站的班次的应用程序,尽管我的代码可以运行,但是我很难从API网址获取所需的值。 (我已经使用其他API网址对其进行了测试,并且可以正常工作)
这是我的代码
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
class DeparturesList extends Component {
state = { departs: [] };
componentWillMount() {
axios.get('https://extranet.trainose.gr/services/passenger_public/mobile_app/ajax.php?c=dromologia&op=vres_dromologia&apo=ΛΑΡΙ&pros=ΘΕΣΣ&date=2018-01-10&rtn_date=undefined-undefined-&travel_type=1&trena%5B%5D=apla&trena%5B%5D=ic&trena%5B%5D=ice&trena%5B%5D=bed&time=23%3A59&time_type=anaxwrhsh&rtn_time=23%3A59&rtn_time_type=anaxwrhsh')
.then(response => this.setState({ departs: response.data }));
}
renderDepartures() {
return this.state.departs.map(depart => <Text>{depart.data.metabash.segments.treno}</Text>);
}
render() {
console.log(this.state);
return (
<View>
{this.renderDepartures()}
</View>
);
}
}
export default DeparturesList;
任何帮助将不胜感激!
答案 0 :(得分:1)
首先,您应该查看从服务器获得的响应。首先,response.data
不是出发地列表,response.data.metabash
是您要寻找的。
以下是响应的结构:
{
"status": int,
"message": String,
"data": {
"metabash": [{
ttt: String,
segments: Array<Segments>
}],
},
}
要获取嵌套值,可以使用类似以下内容的
:this.state.departs.map(depart => depart.segments.map(segment => <Text>{
segment.treno
}</Text>));
答案 1 :(得分:0)
好的,所以尝试一下,并进行了大量研究,但尝试失败了,我得到了我想要的!!!
这是我的代码
import React from 'react';
import { AppRegistry, FlatList, ActivityIndicator, Text, View } from 'react-native';
import Header from './src/components/Header';
export default class FetchExample extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true };
}
componentDidMount() {
return fetch('https://extranet.trainose.gr/services/passenger_public/mobile_app/ajax.php?c=dromologia&op=vres_dromologia&apo=%CE%9B%CE%91%CE%A1%CE%99&pros=%CE%98%CE%95%CE%A3%CE%A3&date=2018-01-10&rtn_date=undefined-undefined-&travel_type=1&trena%5B%5D=apla&trena%5B%5D=ic&trena%5B%5D=ice&trena%5B%5D=bed&time=23%3A59&time_type=anaxwrhsh&rtn_time=23%3A59&rtn_time_type=anaxwrhsh')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data.metabash,
}, () => {
});
})
.catch((error) => {
console.error(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<Header />
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => <Text>{item.segments[0].treno}</Text>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
AppRegistry.registerComponent('trainstation', () => FetchExample);