"Requested keys of a value that is not an object" JSON 和 React Native



我在使用 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

这就是为什么我认为错误是因为我不知道如何正确获取数据。

谢谢!

您以错误的方式访问属性。将dataSource更改为

this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson['Spot[]']),
});

您需要使用括号表示法访问您的属性。

括号表示法需要一个计算结果为字符串(或可以强制转换为字符串(的表达式,因此您可以使用任何字符序列作为属性名称。字符串可以包含的内容没有限制。

相关内容

最新更新