【问题标题】:Function with fetch returns undefined instead an array (React Native)带有 fetch 的函数返回未定义的数组(React Native)
【发布时间】:2019-12-10 05:12:44
【问题描述】:

我有一个包含一些功能的文件:

const API = {
async getComments() {
   var data = [];
   var url = 'http://url.com/wp-json/wp/v2/comments';
   const serviceResponse = await fetch(
    url,
    )
    .then((serviceResponse) => {
     return serviceResponse.json();
   } )
    .catch((error) => console.warn("fetch error:", error))
    .then((serviceResponse) => {
      for (i in serviceResponse) {
        data.push({
         "key": serviceResponse[i]['id'].toString(),
         "name": serviceResponse[i]['author_name'],
         "content": serviceResponse[i]['content']['rendered'].replace(/<(.|\n)*?>/g, ''),
         "gravatar": serviceResponse[i]['author_avatar_urls']['96'],
         "date": serviceResponse[i]['date'].replace('T', ' ')
        });
      }
      global.comments = data;
      return data;
   });
 }
}

export { API as default }

在另一个文件中,我包含该文件,然后进行调用:

var comments = await API.getComments(key);
console.log (comments);

但我收到未定义,我尝试使用绑定创建一个函数: this.newGetComments = API.getComments.bind(this);结果相同。我使用了一个全局变量,但我想删除全局变量。

【问题讨论】:

  • 嗨@Enrique,您收到的内容未定义。 global 变量?或getComments() ?
  • 您忘记在getComments 中返回数据。尝试在getComments末尾返回serviceResponse
  • 谢谢,我的退货行错了,抱歉我没看到那个细节

标签: javascript reactjs react-native asynchronous fetch


【解决方案1】:

/* Few suggestions;
1. you  are not returning anything from the getComments method. Please return fetch(url) response.
2. you should return  something from the catch block to handle the error.
*/


const API = {
  async getComments() {
    var url = 'http://url.com/wp-json/wp/v2/comments';
    var response = await fetch(url)
      .then(serviceResponse => {
        return serviceResponse.json();
      })
      .then(serviceResponse => {
        let data = [];
        
        // rest of your code.
        
        return { success: true, data };
      })
      .catch(error => {
        console.warn('fetch error:', error);
        return { success: false, error };
      });
    return response
  },
};

var comments = await API.getComments(key);
if (comments.success) {
  // handle the success case  comments.data
} else {
  // handle the Error case  comments.error
}

console.log(comments);

【讨论】:

  • 很抱歉,是的,退货行错了,谢谢。我会在错误情况下添加响应
【解决方案2】:

异步函数总是返回一个承诺,因为您没有从 getComments 方法返回任何内容,该函数会自动解析并返回 undefined(Promise.resolve(undefined))。您需要从 getComments 方法返回 serviceResponse 以获取 fetch api 的响应。

【讨论】:

    【解决方案3】:

    您可以尝试以下方法:

    async componentDidMount() {
       let data = [];
       const result = await this.getComments();
       const jsonData = await result.json();
       console.log('Result ==> ', jsonData.serviceResponse);
    
       jsonData.serviceResponse.map(data => 
          data.push({
                     "key": data['id'].toString(),
                     "name": data[i]['author_name'],
                     "content": data[i]['content']['rendered'].replace(/<(.|\n)*?>/g, ''),
                     "gravatar": data[i]['author_avatar_urls']['96'],
                     "date": data[i]['date'].replace('T', ' ')
                   })
       );
       console.log('Data ==> ', data);
    }
    
    async getComments() {
       const result = await fetch('http://url.com/wp-json/wp/v2/comments', {method: 'GET'});
       return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2020-11-03
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      相关资源
      最近更新 更多