首页 > 解决方案 > 在反应中获取返回未定义

问题描述

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

标签: javascriptreactjsfetch

解决方案


基本上,您的问题是您在fetchingetCategory解决之前设置状态。为了解决这个问题,你可以等待它的结果——

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

推荐阅读