目标
我的目标是调用 componentDidMount()
函数从另一个名为 getUserPlaylists()
的方法返回一些值。
问题
我遇到的问题是 componentDidMount()
向我显示了 undefined
的值,而 getUserPlaylists()
向我显示了一个数组的结果。
实际结果
代码
在 Spotify.js 文件中,我有以下代码:
const clientId = 'Cleint ID Here';
const redirectUri = 'http://localhost:3000/';
let accessToken;
let userId;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiryInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiryInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiryInMatch[1]);
window.setTimeout(() => accessToken = '', expiresIn * 10000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
async getUserPlaylists() {
await Spotify.getCurrentUserId().then(userId => {
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
fetch(` https://api.spotify.com/v1/users/${userId}/playlists`, {
headers : headers
})
.then(res => res.json())
.then(res => {
if(!res.items) {
return [];
} else {
console.log(res.items)
return res.items;
}
})
})
},
getCurrentUserId() {
if (userId) {
return new Promise((resolve) => {
resolve(userId);
})
} else {
return new Promise((resolve) => {
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
return fetch("https://api.spotify.com/v1/me", { headers: headers })
.then(res => res.json())
.then(jsonRes => {
userId = jsonRes.id;
resolve(userId);
});
})
}
}
}
export { Spotify };
总结
我的 app.js 文件中有 3 个可以作为方法调用的对象。
以下是我在 app.js 文件中调用 componentDidMount() 的方式:
async componentDidMount() {
const val = await Spotify.getUserPlaylists();
console.log(val)
}
预期结果
componentDidMount()
应该返回与 getUserPlaylists()
相同的值
问题
我不明白为什么 componentDidMount() 返回 undefined
的值?
答案 0 :(得分:3)
因为你没有从 getUserPlaylists
async getUserPlaylists() {
// here return missed
return await Spotify.getCurrentUserId().then(userId => {
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
// here return too
return fetch(` https://api.spotify.com/v1/users/${userId}/playlists`, {
headers : headers
})
.then(res => res.json())
.then(res => {
if(!res.items) {
return [];
} else {
console.log(res.items)
return res.items.map(playlist => ({
playlistId: playlist.id,
playListName: playlist.name
}));
}
})
})
},
你可以简单地使用下面的代码,它的作用相同
async getUserPlaylists() {
// here return missed
try {
const userId = await Spotify.getCurrentUserId()
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
// here return too
const result = await fetch(` https://api.spotify.com/v1/users/${userId}/playlists`, { headers })
const res = await result.json()
if(!res.items) return [];
console.log(res.items)
return res.items.map(playlist => ({ playlistId: playlist.id, playListName: playlist.name }));
} catch(err) {
console.log({ err })
}
}