我在应用程序中显示api数据时遇到了问题,我觉得这与我想要映射数据的方式有关。当我使用我的第一个api时,它工作了,但它不是正确的,因为它显示了所有的俱乐部信息,而不是一个俱乐部。这是邮递员:

这里是控制台:

这是应用程序中显示的内容:

我遇到的问题是,当我使用允许我获取单个俱乐部数据的第二个api链接时,我在映射它时遇到错误。
这是我的代码,我唯一改变的是应用程序接口链接,我也尝试使用c.club.numberOfCheckIns,但它也不起作用。
class Profile extends React.Component {
constructor(props) {
super(props)
this.state = {
clubInfo: []
};
}
componentDidMount() {
this._get('http://ec2-3-15-176-119.us-east-2.compute.amazonaws.com:8080/clubs/get/1').then(
data => {
this.setState({ clubInfo: data })
}
)
}
_get = async (endpoint) => {
const res = await fetch(endpoint, {
headers: {
'Content-Type': 'application/json',
'Access-Token': '1*adminaccesstoken'
}
})
const data = await res.json();
console.log(data)
return data;
}
renderClubData() {
return this.state.clubInfo.map((c, index) => {
const { clubId, name, city, country, email, verified } = c //destructuring
return (
<View key={c.clubId}>
<Text
bold
size={20}
color="#B8AA5B"
style={{ marginBottom: 4 }}
>{c.numberOfCheckIns}
</Text>
</View>
)
})
}
render() {
return (
<Block flex style={styles.profile}>
<Block flex>
<ImageBackground
source={{ uri: Images.EventPhoto }}
style={styles.profileContainer}
imageStyle={styles.profileBackground}
>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ width, marginTop: '55%' }}
>
<Block flex style={styles.profileCard}>
<Block style={styles.info}>
<Block middle style={{ marginTop: 10, paddingBottom: 10 }} row space="between">
<Block middle>
{this.renderClubData()}
<Text size={12}>CHECK-INS</Text>
</Block>这是邮递员:

发布于 2019-12-22 03:12:43
问题在于您处理this.state.clubInfo.map()方法的方式。为了使用map方法,您需要传递一个数组。
这就是它以前工作的原因,因为您向this.state.clubInfo.map()发送了一个数据数组。
如下所示更改您的renderClubData(),因为现在您将获得一个对象作为API请求的结果。
renderClubData() {
return (
<View key={c.clubId}>
{
this.state.clubInfo.club.numberOfCheckIns &&
<Text bold size={20} color="#B8AA5B" style={{ marginBottom: 4 }}>
{this.state.clubInfo.club.numberOfCheckIns}
</Text>
}
</View>
)
}@DevAS也是对的。您可以尝试使用[this.state.clubInfo].map(),如下所示:
renderClubData() {
return [this.state.clubInfo].map((c, index) => {
return (
<View key={c.club.clubId}>
<Text bold size={20} color="#B8AA5B" style={{ marginBottom: 4 }} >
{c.club.numberOfCheckIns}
</Text>
</View>
)
})
}我希望这会对你有所帮助。
https://stackoverflow.com/questions/59438865
复制相似问题