reactjs - 如何移动 fetch api 以响应单独的文件
问题描述
我正在从组件中调用一个 api,因为它看起来很丑,想把它移出来,这就是我尝试过的:
之前:(在组件中)
fetch(url)
.then(response => response.json())
.then(data => this.setState({data, loading: false}));
后:
我没有将 fetch 放入组件中,而是将其移至另一个函数:
export function getData ( url) {
fetch(url)
.then(response => response.json())
.then(data => {
return data;
})
}
我正在
getData(url)
从组件调用,但有些不对劲,我没有看到任何错误,但它不起作用
有什么想法吗 ?
解决方案
它不起作用,因为您实际上并没有在 getData 中返回任何内容。箭头函数中的 return 不返回覆盖函数,而只是返回箭头函数。
你可以做这样的事情来解决它:
export function getData ( url) {
return fetch(url).then(response => response.json())
}
并像这样使用返回的承诺:
getData("http://...").then(result => console.log(result))