我想访问JSON对象中的数据,但在这种情况下我不知道该怎么做。 1.为什么下面的示例不起作用? 2.提取了整个JSON数据后,如何浏览数据以访问必要的元素?我什至不知道要尝试什么,甚至不知道在代码中的哪个地方都可以这样做,因为我什至无法访问一个简单的数据。
以下作品:
dataSource: responseJson.shosfc.weekday[7]
renderItem={({item}) => <Text>{item.min}</Text>}
不是。 为什么?
我所做的只是简单地移动.shosfc.weekday[7]
dataSource: responseJson
renderItem={({item}) => <Text>{item.shosfc.weekday[7].min}</Text>}
JSON API:https://api.myjson.com/bins/18o9sd
第二个错误:
TypeError: Cannot read property 'weekday' of undefined
This error is located at:
in CellRenderer (at VirtualizedList.js:688)
in RCTScrollContentView (at ScrollView.js:1007)
in RCTScrollView (at ScrollView.js:1147)
in ScrollView (at VirtualizedList.js:1081)
in VirtualizedList (at FlatList.js:634)
in FlatList (at App.js:42)
in RCTView (at View.js:35)
in View (at App.js:41)
in FetchExample (at renderApplication.js:40)
in RCTView (at View.js:35)
in View (at AppContainer.js:98)
in RCTView (at View.js:35)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:39)
renderItem
injectUpdate.js:71:4
FlatList._this._renderItem
FlatList.js:628:13
CellRenderer.render
VirtualizedList.js:1741:20
CellRenderer.proxiedMethod
createPrototypeProxy.js:44:29
下面是整个代码。
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
// make an API call in the beginning
componentDidMount(){
return fetch('https://api.myjson.com/bins/wa759')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.shosfc.weekday[7]
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 50}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:50}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.min}</Text>}
// keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
答案 0 :(得分:1)
FlatList
组件仅接受道具data
的数组。
似乎responseJson.shosfc.weekday[7]
是一个数组,而responseJson
是一个对象。
来源:https://facebook.github.io/react-native/docs/flatlist#data
答案 1 :(得分:1)
<FlatList>
需要将数据作为对象列表。通过responseJson.shosfc.weekday[7]
时就是这种情况:
[
{ min: 10, type: 'h' },
{ min: 17, type: 'h' },
{ min: 24, type: 'ht' },
{ min: 30, type: 'h' },
{ min: 35, type: 'ht' },
{ min: 40, type: 'h' },
{ min: 44, type: 'h' },
{ min: 48, type: 'h' },
{ min: 53, type: 'ht' },
{ min: 56, type: 'h' }
]
但是,当您简单地通过responseJson
时,情况并非如此:
{
shosfc: {
weekday: {
'7': [Array],
'8': [Array],
'9': [Array],
'10': [Array],
'11': [Array],
'12': [Array],
'13': [Array],
'14': [Array],
'15': [Array],
'16': [Array],
'17': [Array],
'18': [Array],
'19': [Array],
'20': [Array],
'21': [Array],
'22': [],
'23': [],
},
// [...]
},
// [...]
}