gpt4 book ai didi

javascript - React 状态值未定义

转载 作者:行者123 更新时间:2023-12-02 23:30:55 24 4
gpt4 key购买 nike

我正在构建一个音乐播放器应用程序,并且我有一个函数可以从组件状态下的对象中获取值。

当我将该值赋予函数时,它会打印未定义的值,而不是该值本身,因此该函数无法使用未定义的值。

这就是我打印状态时firstSong 组件的样子:

{
Title: "One Dance",
Artist: "Drake",
Length: "4:03",
Path:
"/home/songs/Drake - One Dance ft. EMØ.mp3"
}

这是完整的组件代码:

import React, { Component } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faBackward,
faPlay,
faForward,
faStop
} from "@fortawesome/free-solid-svg-icons";
import styled from "styled-components";
import axios from "axios";

const CardStyling = styled.div`
.card-body {
width: 100%;
}

#song-header {
margin-bottom: 25px;
}

#artist {
margin-bottom: 25px;
}

#time {
margin-bottom: 25px;
}
`;

let display = "none";
const firstSongApi = "http://localhost:4001/getFirstSong";
const playSongApi = "http://localhost:4001/playSong";

export default class SongInfo extends Component {
constructor() {
super();
this.state = {
firstSong: this.getFirstSong(firstSongApi),
isPlaying: false
};
}

getFirstSong = async firstSongApi => {
const request = await axios({
method: "get",
url: firstSongApi,
headers: {}
});
try {
let firstSong = request.data.firstSong;
this.setState({
firstSong: firstSong
});
} catch (error) {
console.error(error);
}
};

playOrPauseSong = path => {
console.log(path);
};

render() {
{
this.playOrPauseSong(this.state.firstSong.path);
}
return (
<CardStyling className="card">
<div className="card-body">
<h3 id="song-header">{this.state.firstSong.Title}</h3>
<h5 id="artist">By: {this.state.firstSong.Artist}</h5>
<h5 id="Time">{this.state.firstSong.Length}</h5>
<button type="button" id="back-btn" className="btn">
<FontAwesomeIcon icon={faBackward} />
</button>
<button
type="button"
id="play-btn"
className="btn"
onClick={() => this.playOrPauseSong(this.state.songLocation)}
>
<FontAwesomeIcon icon={faPlay} />
</button>
<button
type="button"
id="stop-btn"
className="btn"
style={{ display: display }}
>
<FontAwesomeIcon icon={faStop} />
</button>
<button type="button" id="next-btn" className="btn">
<FontAwesomeIcon icon={faForward} />
</button>
</div>
</CardStyling>
);
}
}


我希望该函数能够获取真实的路径值而不是未定义的,提前谢谢您!

最佳答案

确保您的状态如下所示,并且路径将正确记录在 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>
)
}

关于javascript - React 状态值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com