很抱歉,如果问题的措词奇怪,还不太知道如何形容。我正在尝试制作它,因此当您单击专辑名称时,它会显示该专辑的所有曲目;目前,它可以正常登录到控制台,但是当我尝试渲染它时,仅显示一个轨道名称,或者根本不显示任何轨道(这是我当前所在的位置)。这是我的搜索组件,非常感谢您提供所有帮助。
export default class SearchScreen extends Component {
constructor() {
super();
this.state = {
value: '',
searchClicked: false,
backClicked: false,
albumInfoClicked: false,
searchAlbums: {
response: []
},
albums: [],
tracks: ['']
};
this.handleChange = this.handleChange.bind(this);
this.searchAlbums = this.searchAlbums.bind(this);
}
handleChange(event) {
this.setState({
value: event.target.value
});
}
//Gets list of albums
searchAlbums() {
spotifyWebApi.searchAlbums(this.state.value)
.then((response) => {
this.setState({
albums: response.albums.items ,
searchClicked: true,
});
});
}
render() {
var albumTrackInfo = [];
var albumInfoClicked = false;
//this is the part that matters
if(searchClicked) {
return this.state.albums.map((t, counter) => {
return t.artists.map((artistsArray) => {
var albumID = t.id;
const albumInfo = () => {
albumInfoClicked = true;
console.log(albumID)
//Gets list of tracks for the album ID
spotifyWebApi.getAlbumTracks(albumID)
.then(response => {
albumTrackInfo = response.items
return albumTrackInfo.map((albumTracks) => {
this.setState({
tracks: albumTracks.name,
albumInfoClicked: true
})
//this isnt getting renderd
return (
<div>
<li>{this.state.tracks}</li>
</div>
)
})
})
}
return (
<div class="result-container row">
<div class="row">
<img src={t.images[0].url} alt={t.name} class="image" height="256px" width="256px" data-toggle="tooltip" data-placement="top" title="Hooray!" /> {counter}
<div class="middle">
<div key={t.name} class="text">
<a href="#" onClick={() => albumInfo()}> {t.id} <br></br> {t.name} </a><br></br>
By: {artistsArray.name} <br></br>
<i class="fas fa-play"></i>
</div>
</div>
</div>
</div>
)
});
});
}
答案 0 :(得分:2)
我不熟悉Spotify api,但我想问题可能出在这条逻辑上
spotifyWebApi.getAlbumTracks(albumID)
.then(response => {
albumTrackInfo = response.items
return albumTrackInfo.map((albumTracks) => {
this.setState({
tracks: albumTracks.name,
albumInfoClicked: true
})
您正在将轨道的状态设置为一个特定的轨道名称。也许您想尝试这样的事情(更新)
spotifyWebApi.getAlbumTracks(albumID)
.then(response => {
albumTrackInfo = response.items
let songsObject = albumTrackInfo.reduce((acc, val) => {
const name = val.name;
return {
...acc,
[name]: name
};
}, {});
let songsArray = Object.keys(songsObject);
this.setState({
tracks: songsArray
})
})
这应该为您提供该api中所有歌曲名称的数组,并更新曲目的状态。
更新
Damian G。。我想您可能更喜欢以这种方式获取数据-这将为您提供一系列歌曲名称作为字符串。
spotifyWebApi.getAlbumTracks(albumID)
.then(response => {
albumTrackInfo = response.items
let newArray = albumTrackInfo.map((albumTrack) => {return albumTrack.name});
this.setState({
tracks: newArray
})
})
或者从风格上讲是一个更好的解决方案:
spotifyWebApi.getAlbumTracks(albumID)
.then(response => {
albumTrackInfo = response.items
let songsArray = albumTrackInfo.map((albumTrack) => {return albumTrack.name});
return songsArray;
}).then(songsArray => {
this.setState({
tracks: songsArray
})
})