【问题标题】:Trying to figure out why my react App is not working试图弄清楚为什么我的反应应用程序不起作用
【发布时间】:2021-09-09 03:21:06
【问题描述】:

我在使用 spotify 的项目时遇到了一些问题,每次我尝试搜索艺术家时,都会收到以下消息:非法 redirect_uri。我还得到了一份令我感到困惑的问题清单。有人有什么建议吗?这是我的代码。

src\Components\SearchBar\SearchBar.js 第 25:5 行:重复名称“handleTermChange”no-dupe-class-members

src\util\Spotify.js 第 1:7 行:“clientId”被分配了一个值,但从未使用过 no-unused-vars 第 2:7 行:“redirectUri”被分配了一个值,但从未使用过 no-unused-vars 第 25:31 行:意外的模板字符串表达式 no-template-curly-in-string 第 31:15 行:“accessToken”被赋值,但从未使用 no-unused-vars 第 32:22 行:意外的模板字符串表达式 no-template-curly-in-string 第 34:27 行:意外的模板字符串表达式 no-template-curly-in-string 第 57:15 行:“accessToken”被赋值,但从未使用 no-unused-vars 第 58:41 行:意外的模板字符串表达式 no-template-curly-in-string 第 64:13 行:“userId”被分配了一个值,但从未使用过 no-unused-vars 第 65:27 行:意外的模板字符串表达式 no-template-curly-in-string 第 72:23 行:“playlistId”被分配了一个值,但从未使用过 no-unused-vars

import React from 'react';

import './SearchBar.css';

class SearchBar extends React.Component {
    constructor(props) {
        super(props);

        this.state ={
            term: ''
        }

        this.search = this.search.bind(this);
        this.handleTermChange = this.handleTermChange.bind(this);
    }

    search() {
        this.props.onSearch(this.state.term);
    }

    handleTermChange(event) {
        this.setState({term: event.target.value});
    }

    handleTermChange(event) {
        this.setState({term: event.target.value});
    }

    render() {
        return (
            <div className="SearchBar">
  <input onChange={this.handleTermChange} placeholder="Enter A Song, Album, or Artist" />
  <button className="SearchButton" onClick={this.search} >SEARCH</button>
</div>
        )
    }
}

export default SearchBar;
const clientId = '5e56a43c5001426189eda044053e2d30';
const redirectUri = 'http://localhost:3000/'

let accessToken;

const Spotify = {
    getAccessToken() {
        if (accessToken) {
            return accessToken;
        }

        // check for access token match
        const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
        const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

        if(accessTokenMatch && expiresInMatch) {
            accessToken = accessTokenMatch[1];
            const expiresIn = Number(expiresInMatch[1]);
            //This clears the parameters, allowing us to grab a new access token when it expires.
            window.setTimeout(() => accessToken = '', expiresIn * 1000);
            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;
        }
    },

    search(term) {
        const accessToken = Spotify.getAccessToken();
        return fetch('https://api.spotify.com/v1/search?type=track&q=${term}', 
        {headers: { 
            Authorization:'Bearer ${accessToken}'
         }
        }).then(response => {
            return response.json();
        }).then(jsonResponse => {
            if(!jsonResponse.tracks) {
                return [];
            }
            return jsonResponse.tracks.items.map(track => ({
                id: track.id,
                name: track.name,
                artist: track.artists[0].name, 
                album: track.album.name,
                uri: track.uri
            }));
        }) ;
    },

    savePlayList(name, trackUris) {
        if(!name || !trackUris.length) {
            return;
        }

        const accessToken = Spotify.getAccessToken();
        const headers = {Authorization: 'Bearer ${accessToken}'};
        let userId;

        return fetch('https://api.spotify.com/v1/me', {headers:headers}
        ).then(response => response.json()
        ).then(jsonResponse => {
            userId = jsonResponse.Id;
            return fetch ('https://api.spotify.com/v1/users/${user_id}/playlists',
            {
                headers:headers,
                method:'POST',
                body: JSON.stringify({name: name})
            }).then(response => response.json()
            ).then(jsonResponse => {
                const playlistId = jsonResponse.id;
                return fetch('https://api.spotify.com/v1/users/${userId}/playlists',
                {
                    headers: headers,
                    method: 'POST',
                    body: JSON.stringify({Uris: trackUris})
                });
            })
        })
    }
}

export default Spotify;
import React from 'react';
import './App.css';
import SearchBar from '../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';
import Spotify from '../../util/Spotify';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchResults: [],
         playlistName: 'My Playlist',
         playlistTracks: []
    };
    
    this.addTrack = this.addTrack.bind(this);
    this.removeTrack = this.removeTrack.bind(this);
    this.updatePlaylistName = this.updatePlaylistName.bind(this);
    this.savePlaylist = this.savePlaylist.bind(this);
    this.search = this.search.bind(this);
  }

  addTrack(track) {
    let tracks = this.state.playlistTracks;
    if(tracks.find(savedTrack => savedTrack.id === track.id)){
      return;
    }

    tracks.push(track);
    this.setState({playlistTracks: tracks})
  }

  removeTrack(track) {
    let tracks = this.state.playlistTracks;
    tracks = tracks.filter(currentTrack => currentTrack.id !== track.id);

    this.setState({playlistTracks: tracks});
  }

  updatePlaylistName(name) {
    this.setState({playlistName: name});
  }

  savePlaylist() {
    const trackUris = this.state.playlistTracks.map(track => track.uri);
    Spotify.savePlaylist(this.state.playlistName, trackUris).then(()=> {
      this.setState({
        playlistName: 'New Playlist',
        playlistTracks: []
      })
    })
  }

  search(term) {
    Spotify.search(term).then(searchResults => {
      this.setState({searchResults: searchResults})
    })
  }


  render() {
    return (
      <div>
  <h1>Ja<span className="highlight">mmm</span>ing</h1>
  <div className="App">
    <SearchBar onSearch={this.search} /> 
    <div className="App-playlist">
      <SearchResults searchResults={this.state.searchResults}
        onAdd={this.addTrack} /> 
      <Playlist playstName={this.state.playlistName}
        playlistTracks={this.state.playlistTracks} 
        onRemove = {this.removeTrack}
        onNameChange ={this.updatePlaylistName}
        onSave = {this.savePlaylist} /> 
    </div>
  </div>
</div>
    )
  }
}

export default App;

【问题讨论】:

  • 您在此处显示的大多数问题都来自eslint,在使用Create React App 时会自动配置。例如“src\Components\SearchBar\SearchBar.js Line 25:5: Duplicate name ‘handleTermChange’ no-dupe-class-members”;在该文件的该行中,您可以看到您已经连续定义了两次handleTermChange。 Eslint 基本上被配置为发现常见错误或反模式并警告你以保持你的代码干净和可维护。
  • 所有这些错误/警告都是不言自明的。例如:您的 SearchBar 组件中有 两个 handleTermChange 方法,这是 "Duplicate name 'handleTermChange' no-dupe-class-members" 警告您关于。
  • 至于“非法redirect_uri”错误,the SO post "Spotify API Illegal redirect_uri"可能包含一些有用的信息。
  • 同样值得注意的是 eslint——大多数编辑器都可以配置为直接在编辑器中显示这些错误和警告,这样你就可以看到它们并立即解决它们,而不是等待你的构建将它们记录到终端和/或浏览器控制台的过程。
  • 非常感谢!这是解决我的问题的解决方案之一!

标签: javascript html css reactjs


【解决方案1】:

您的Template literals 声明错误,它们都需要以反引号 (`) 开头和结尾

应该是:

const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`

带 (`) 而不是 (')

你的另一个 Template literals 以此类推,它应该都以反引号 (`) 开头和结尾;

return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`,
Authorization:`Bearer ${accessToken}`

等等……

另外,删除handleTermChange 函数之一。

【讨论】:

  • 非常感谢!这是解决我的问题的解决方案之一!
【解决方案2】:

首先,您有 2 个handleTermChange。删除一个主题。

第二,你用错了Template literals。所以clientId 不会用。像这样更新{``}

const accessUrl = {`https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`}

【讨论】:

  • 非常感谢!这是解决我的问题的解决方案之一!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 2021-05-29
相关资源
最近更新 更多