[英]Working with promises in a React class component
I have this module to fetch data using the Spotify API:我有这个模块来使用 Spotify API 获取数据:
const Spotify = {
getAccessToken() { ... },
searchTrack(searchTerm) {
const accessToken = Spotify.getAccessToken();
return fetch(
`https://api.spotify.com/v1/search?q=${searchTerm}&type=track`,
{
headers: { Authorization: `Bearer ${accessToken}` },
}
)
.then((response) => response.json())
.then((jsonResponse) => jsonResponse.tracks.items[3].name);
},
};
I then import it to this class component and try to display the data:然后我将它导入到这个类组件并尝试显示数据:
termToSearch() {
return(Spotify.searchTrack(this.props.searchTerm))
}
But I keep getting this error:但我不断收到此错误:
Uncaught Error: Objects are not valid as a React child (found: [object Promise])...
Also, when I alternately try to set the state in the function, I get an infinite loop of calls to the fetch API.此外,当我交替尝试在函数中设置状态时,我得到一个对 fetch API 的无限循环调用。 I'm now really stuck on how to render this returned data.
我现在真的很纠结如何渲染这个返回的数据。
If I understood correctly, you are trying to return the response getting from the fetch
API call.如果我理解正确,您正在尝试返回从
fetch
API 调用中获得的响应。 Fetch will always return a promise and that is the reason you are getting Uncaught Error: Objects are not valid as a React child (found: [object Promise])...
Fetch 将始终返回一个承诺,这就是您收到
Uncaught Error: Objects are not valid as a React child (found: [object Promise])...
You can use async and await
to the function so that the promise will be resolved and return the result.您可以对函数使用
async and await
,以便解决 Promise 并返回结果。
async function fetchAPI() { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const result = await response.json(); return result; } catch (error) { console.error(error); } } async function api() { const result = await fetchAPI(); console.log(result); } api();
I think you can change your method to something like this.我认为您可以将方法更改为这样的方法。
async searchTrack(searchTerm) {
let res;
const accessToken = Spotify.getAccessToken();
const data = await fetch(`https://api.spotify.com/v1/search?q=${searchTerm}&type=track`, {
headers: { Authorization: `Bearer ${accessToken}` }
});
const jsonResponse = await data.json();
return jsonResponse.tracks.items[3].name;
}
When you are calling the method you need to add await
当您调用该方法时,您需要添加
await
async termToSearch() {
return(await Spotify.searchTrack(this.props.searchTerm))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.