2 回答

TA贡献1796条经验 获得超7个赞
确保您的状态如下所示,并且路径将正确记录在 playOrPauseSong 中;
this.state = {
firstSong: {
title: "One Dance",
artist: "Drake",
length: "4:03",
path:
"/home/songs/Drake - One Dance ft. EMØ.mp3"
}
}
playOrPauseSong = path => {
console.log(path)
}
render(){
return(
<div>
{this.playOrPauseSong(this.state.firstSong.path)}
</div>
)
}

TA贡献1793条经验 获得超6个赞
render() {
{
this.playOrPauseSong(this.state.firstSong.path);
}
...
未定义的原因是您firstSong仍在接受网络请求,即async方法,因此不会有任何firstSong或firstSong.path,因此它是undefined. 因此,您可以更新为以下内容
render() {
{
this.state.firstSong.path && this.playOrPauseSong(this.state.firstSong.path);
}
所以它的作用是,当没有时path,不会调用该方法,并且会在网络调用返回结果时调用它,但实际上,您应该引入另一个标志来跳过调用,this.playOrPauseSong因为您的组件将被保留重新渲染,您不会希望每次重新渲染时都继续调用它
更新:
让我们稍微重组一下
我们可以使firstSongas的初始状态null并单独调用 getFirstSong,因此您的构造函数应如下所示
constructor() {
super();
this.state = {
firstSong: null,
isPlaying: false
};
this.getFirstSong(firstSongApi);
}
然后对于您的render方法,您将进行检查,firstSong因为在初始加载时,firstSong 将为空,因此更新到以下内容
render() {
{
this.state.firstSong && this.playOrPauseSong(this.state.firstSong.path);
}
添加回答
举报