【发布时间】:2017-08-22 10:43:43
【问题描述】:
我遇到了一个我无法解决的 React Native 问题,很可能是因为我对 React 和 JavaScript 还很陌生,所以我可能没有所有的“密钥”。哈哈
首先,这是我的 JSON 的结构:
{ "Spot[]": [
{"id":1,"name": "Relais Villenus"},
{"id":2, "name": "Random"}
]}
到目前为止,我还没有开始处理很多 JSON,但他们从来都不是这样的,这让我失去了信心!
我的班级请求数据:
class ListScreen extends Component{
static navigationOptions = {
tabBarLabel: 'Liste',
};
constructor(props) {
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.Spot),
});
})
.catch((error) => {
console.error(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData.name}</Text>}
/>
</View>
);
}
}
根据我在这里或在 GitHub 上阅读的内容,我尝试了不同的方法,例如
dataSource: ds.cloneWithRows(responseJson.Spot[]),
或者像这样:
dataSource: ds.cloneWithRows(responseJson),
在视图中:
renderRow={(rowData) => <Text>{rowData.Spot.name}</Text>}
或
renderRow={(rowData) => <Text>{rowData.Spot[name]}</Text>}
我的代码使用这个 JSON:https://facebook.github.io/react-native/movies.json
这就是为什么我认为错误是因为我不知道如何正确获取数据。
谢谢!
【问题讨论】:
-
试试这个
ds.cloneWithRows(responseJson['Spot[]']) -
哦,非常感谢哈桑! :) 有用 !我确实尝试过 responseJson.['Spot[]'])。有一点:FML!再次感谢!
标签: javascript arrays json reactjs react-native