javascript - 在反应中获取返回未定义
问题描述
我正在尝试将 WordPress API 与 react 一起使用,但它返回 id 而不是标签名称,因此我试图通过另一个 API 调用来获取标签名称。但它一直返回未定义。当我在 getCategory() 中的 fetch 之前添加 return 时,它只会出错。
componentDidMount() {
const URL =
'https://public-api.wordpress.com/wp/v2/sites/sitename/posts/';
fetch(URL)
.then(res => res.json())
.then(posts => {
const post = posts.map(post => {
return {
...post,
categories: this.getCategory(...post.categories)
};
});
this.setState({ posts: post });
console.log(post);
})
.catch(err => console.log(err));
}
getCategory(id) {
const URL = `https://public-api.wordpress.com/wp/v2/sites/sitename/categories/${id}`;
fetch(URL)
.then(data => data.json())
.then(res => res.name)
}
解决方案
基本上,您的问题是您在fetch
ingetCategory
解决之前设置状态。为了解决这个问题,你可以等待它的结果——
componentDidMount() {
const URL = 'https://public-api.wordpress.com/wp/v2/sites/sitename/posts/';
fetch(URL)
.then(res => res.json())
.then(posts => {
return Promise.all(posts.map(async post => {
return {
...post,
categories: await this.getCategory(...post.categories)
};
}));
})
.then(posts => this.setState({ posts: posts }))
.catch(err => console.log(err));
}
getCategory(id) {
const URL = `https://public-api.wordpress.com/wp/v2/sites/sitenameress.com/categories/${id}`;
return fetch(URL)
.then(data => data.json())
.then(res => res.name)
}
推荐阅读
- c# - C# ArgumentException Image.FromStream 在一个套接字上具有多个发送
- attributeerror - bbc-microbit:micropython AttributeError:“str”对象没有属性“partition”
- c - 什么将空字符串复制到另一个字符串?
- javascript - 量角器错误:预期 null 等于“某个值”
- dart - runApp 使用有状态小部件引发异常
- c - 有没有一种快速的方法来消除 Visual Studio 中 C 程序中未使用的类型?
- apache-spark - Spark如何计算字符串列的均值和标准差
- elasticsearch - 用于设置索引“否”的 Elasticsearch 使用哪种类型,关键字或文本?
- javascript - 如何使用带有 IE11 的 Windows Powershell 注入 JavaScript
- here-api - 使用Here maps javascript查找折线的长度(英里或公里)