【发布时间】: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