您好,我目前正在使用我的rails api与React native一起检索用户微博数据。数据呈现在我的日志中,但在react native中变为空白。老实说,我不确定我在做什么错。有人可以帮忙吗?也许是JSON问题?
这是JSON数据:
[{"id":4,"content":"fool","user_id":1,"created_at":"2018-06-21T00:50:08.343Z","updated_at":"2018-06-21T00:50:08.343Z","picture":{"url":null}},{"id":3,"content":"pool\r\n","user_id":1,"created_at":"2018-06-21T00:50:04.644Z","updated_at":"2018-06-21T00:50:04.644Z","picture":{"url":null}},{"id":2,"content":"cool","user_id":1,"created_at":"2018-06-16T04:26:11.020Z","updated_at":"2018-06-16T04:26:11.020Z","picture":{"url":null}}]
这是我的React Native代码:
import React, { Component } from "react";
import { FlatList, StyleSheet, Text, View, AsyncStorage } from "react-
native";
const ACCESS_TOKEN = 'access_token';
export default class App extends Component {
state = {
data: []
};
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
const response = await fetch("https://example.com/api/users/"+accessToken);
const json = await response.json();
this.setState({ data: json.data });
};
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
keyExtractor={item => item.toString()}
renderItem={({ item }) =>
<Text>
//also tried {`${item.content}`}, didn't work
{`${item.microposts.content}`}
</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 15,
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
}
});
答案 0 :(得分:0)
}
请通过这样声明renderItem来优化代码
renderItem={({ item }) => <Text>{item.microposts && item.microposts.content}</Text>}