gpt4 book ai didi

javascript - 在 react 中获取未定义的返回

转载 作者:行者123 更新时间:2023-11-28 17:30:59 25 4
gpt4 key购买 nike

我尝试将 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)
}

最佳答案

基本上,您的问题是您在 getCategory 中的 fetch 解析之前设置状态。要解决这个问题,您可以等待其结果 -

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)
}

关于javascript - 在 react 中获取未定义的返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50439387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com