【发布时间】:2021-03-19 00:45:57
【问题描述】:
这里的新开发人员试图创建一个 Spotify 搜索项目来帮助我学习。
我正在学习本教程,以便用户可以使用 spotify 登录我的应用程序。 https://levelup.gitconnected.com/how-to-build-a-spotify-player-with-react-in-15-minutes-7e01991bc4b6
我目前停留在询问您在哪里创建登录按钮的部分。我已经按照代码示例进行了操作,但是当我加载页面时出现错误:
TypeError: Cannot read property 'token' of null
Landing.render
src/components/Landing.js:39
36 | }
37 | render() {
38 | return (
> 39 | <div className="Landing">
| ^ 40 | {!this.state.token && (
41 | <a
42 | className="btn btn--loginApp-link"
这是我的代码的样子
import './Landing.scss';
import React, { Component } from 'react';
export const authUrl = 'https://accounts.spotify.com/authorize';
const clientId = "MY_CLIENT_ID";
const redirectUri = "http://localhost:3000";
const scopes = [
"user-read-currently-playing",
"user-read-playback-state",
];
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function (initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
class Landing extends Component {
componentDidMount() {
let _token = hash.access_token;
console.log(_token)
if (_token) {
this.setState({
token: _token
});
} else {
console.log("no token")
}
}
render() {
return (
<div className="Landing">
{!this.state.token && (
<a
className="btn btn--loginApp-link"
href={`${authUrl}client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join("%20")}&response_type=token&show_dialog=true`}
>
Login to Spotify
</a>
)}
{this.state.token && (
console.log("hello")
)}
</div>
);
}
}
export default Landing;
谁能把我推向正确的方向?
【问题讨论】:
-
您的状态似乎没有被设置。这行
console.log(_token)的输出是什么? -
未定义。
-
是的,所以没有设置状态。如果
_token未定义,则永远不会运行this.setState()。我想你看到“没有令牌”被打印了? -
是的,但我不确定为什么它为空。正如我所说,我对编码很新鲜。但是我按照上面提到的本教程进行操作,这似乎正是他设置的,所以我不确定为什么会看到这个错误
-
嗯,这是因为
this.state未定义。如果您在 Chrome 的开发人员工具中打开控制台并输入this.state.token,您将得到与没有this.state完全相同的错误,因此不可能有this.state.token。您是否尝试过删除 if -if (_token) {?