componentDidMount() 返回一个未定义的值

时间:2021-04-11 21:49:47

标签: javascript reactjs

目标

我的目标是调用 componentDidMount() 函数从另一个名为 getUserPlaylists() 的方法返回一些值。

问题

我遇到的问题是 componentDidMount() 向我显示了 undefined 的值,而 getUserPlaylists() 向我显示了一个数组的结果。

实际结果

enter image description here

代码

在 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 的值?

1 个答案:

答案 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 })
  }
}
相关问题