You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React调用WordPress API获取分类名时Fetch返回undefined求助

解决React中调用WordPress API获取分类名返回undefined的问题

我来帮你梳理下问题根源和解决办法:

核心问题分析

你的代码里有两个关键问题导致拿不到分类名:

  1. getCategory函数没有返回异步结果:fetch是异步操作,你在函数里发起了请求,但没有把Promise返回出去,所以调用this.getCategory(...)时会直接得到undefined。
  2. 同步map无法等待异步请求完成:在posts.map里直接调用异步函数,map会同步执行,不会等待分类请求返回结果,所以最终categories字段要么是undefined,要么是未完成的Promise对象。

修正步骤和代码

第一步:让getCategory返回Promise

修改getCategory,把fetch的链式调用return出去,这样外部可以通过.then()获取分类名:

getCategory(id) {
  const URL = `https://public-api.wordpress.com/wp/v2/sites/sitename/categories/${id}`;
  // 返回fetch的Promise链,最终resolve为分类名
  return fetch(URL)
    .then(data => data.json())
    .then(res => res.name)
    .catch(err => {
      console.log(`获取分类ID ${id} 失败:`, err);
      return '未知分类'; // 请求失败时返回默认值
    });
}

第二步:用Promise.all等待所有异步请求完成

因为每个文章可能对应多个分类,而且每个分类请求都是异步的,所以需要用Promise.all等待所有分类请求完成后,再更新state:

componentDidMount() {
  const URL = 'https://public-api.wordpress.com/wp/v2/sites/sitename/posts/';
  fetch(URL)
    .then(res => res.json())
    .then(posts => {
      // 对每篇文章,创建一个Promise:获取所有分类名后替换原categories字段
      const postPromises = posts.map(post => {
        // 如果文章有多个分类,用Promise.all等待所有分类名返回
        const categoryPromises = post.categories.map(id => this.getCategory(id));
        return Promise.all(categoryPromises)
          .then(categoryNames => {
            return {
              ...post,
              categories: categoryNames // 替换为分类名字符串数组
            };
          });
      });

      // 等待所有文章的分类请求都完成
      return Promise.all(postPromises);
    })
    .then(updatedPosts => {
      this.setState({ posts: updatedPosts });
      console.log(updatedPosts);
    })
    .catch(err => console.log(err));
}

额外说明

  • 如果你的文章只会有一个分类,也可以简化categoryPromises的逻辑,但上面的代码兼容单/多分类场景。
  • 加上catch处理分类请求失败的情况,避免单个分类请求失败导致整个流程中断。

内容的提问来源于stack exchange,提问作者Shakhor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:13:31