[英]Uncaught TypeError: Cannot read property 'setState' of undefined
[英]Spotify Web API: Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
我收到Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
。 我正在尝试使用this.setState
来渲染一些轨道,但仅限于 9 个轨道,想看看是否一切都正确。
这里的代码如下:
import React from 'react';
require('dotenv').config();
// My Steps: //
// 1. Want to fetch for KD Rusha Top Ablums on Spoitify Done
// 2. Limit them to only 9 tracks
// 3. Add play button on top of each track to play 30 sec of the Song
// GO TO SPOTIFY AND GETTING KD RUSHA TOP ABLUMS lIMIT TO 9 SONGS
// WHEN YOU CLICK ON TOP OF THE ABLUMS A PLAY BUTTON ICON WILL SHOW TO INDICATE THAT YOU CAN PLAY 30 SECONDS OF SONG
export default class SpotifyComponent extends React.Component {
constructor(props){
super(props);
this.state = {
artist: null,
};
}
componentWillMount() {
var request = new Request('https://api.spotify.com/v1/artists/5JLWikpo5DFPqvIRi43v5y/', {
method: 'GET',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'text/plain',
'Authorization': 'Access Token Here'
})
});
fetch(request)// fetch the Spotify date from KD Rusha Account
.then(function(response){
var result = response.json()
this.setState({// State artist albums
albums: result,
selectedTrack: [0]
});
console.log(this.setState);
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
});
}
render(){
return(
<ul className="spotify-cantainer">
</ul>
);
}
}
您将需要使用.bind
或.bind
箭头语法=>
来声明您的promise回调。
.then(function(response){
应该是.then((response)=> {
如果不使用箭头功能,则会丢失此上下文。
当你在then
的背景下this
变化,不再是指该组件。 您有两种选择可以解决此问题。
你可以指定this
一个变量,然后使用变量:如
var self = this;
request(...)
.then(function(response) {
self.setState(...)
})
或者,如果您能够使用自己的应用程序,则可以使用箭头功能代替常规功能。 例如
request(...)
.then((response) => {
this.setState(...)
})
原因是箭头功能,默认情况下绑定到范围。 您可以在此处阅读更多信息: https : //toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/#functionality-lexical-scoping-this
这通常发生在我们收到响应代码403
时,根据 Spotify 的 API 文档,这意味着禁止。 要解决此问题,只需在身份验证 URL 中添加您想要获得的响应的 scope 即可开始工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.