Reactjs 如何在平面列表中调用另一个api?
我有一个API,它有标题、主体和用户id,我想在另一个API的帮助下打印用户名。那我怎么做呢? 我在下面列出了这两个APIReactjs 如何在平面列表中调用另一个api?,reactjs,react-native,Reactjs,React Native,我有一个API,它有标题、主体和用户id,我想在另一个API的帮助下打印用户名。那我怎么做呢? 我在下面列出了这两个API //${id} 您可以做的是首先获取帖子并将其保存在变量中。 然后在映射内调用其他api以获取用户数据并将用户数据附加到变量中 示例 fetch('https://jsonplaceholder.typicode.com/posts',) .then(response => { let new_post = [];
您可以做的是首先获取帖子并将其保存在变量中。 然后在映射内调用其他api以获取用户数据并将用户数据附加到变量中 示例
fetch('https://jsonplaceholder.typicode.com/posts',)
.then(response => {
let new_post = [];
let posts = response.json() ;
Promise.all(
posts.map(item => {
fetch('https://jsonplaceholder.typicode.com/users/'+item.userId)
.then(res =>{
item['user'] = res.json() ;
console.log(item)
new_post.push(item)
})
})
)
.then(() => {
this.setState({testing:new_post})
})
})
然后在平面列表中按显示用户名
<FlatList
data={this.state.testing}
renderItem={({item}) =>(
<View>
<Text>other</Text>
<Text>{item.user.email}</Text>
</View>
)
}
/>
我建议阅读关于我没有从response.data获得任何数据的内容。它是“未定义的”,代码中的更改是什么请帮助测量您是否使用fetch或axios…?如果您使用fetch api。。您需要将响应转换为json。。。。我将编辑我的答案,向您展示fetch和axios的工作原理。。。
<FlatList
data={this.state.testing}
renderItem={({item}) =>(
<View>
<Text>other</Text>
<Text>{item.user.email}</Text>
</View>
)
}
/>
axios.get('https://jsonplaceholder.typicode.com/posts',)
.then(response => {})