在这里react新手,
import React, { Component } from "react";
class AudioList extends Component {
constructor(props) {
super(props);
this.audios = [];
this.buttonText = [];
for (let i = 0; i < this.props.songs.length; i++) {
this.audios.push(new Audio(this.props.songs[i].song_url));
this.buttonText.push(String(i));
}
this.state = {
songs: "",
buttonText: this.buttonText
};
}
componentWillMount() {
const songs = [];
for (let i = 0; i < this.props.songs.length; i++) {
this.audios[i].addEventListener("play", () => {
let stateArray = [...this.state.buttonText];
let stateArrayElement = { ...stateArray[i] };
stateArrayElement = "playing";
stateArray[i] = stateArrayElement;
console.log(stateArray);
this.setState({ buttonText: stateArray });
console.log(this.state.buttonText[i]);
});
songs.push(
<div className="song-preview">
<button
className="preview"
onClick={() => this.toggle(this.audios[i])}
>
{this.state.buttonText[i]}
</button>
</div>
);
}
this.setState({
songs: songs
});
}
componentWillUnmount() {
for (let i = 0; i < this.props.songs.length; i++) {
this.audios[i].pause();
}
}
getCurrentAudio() {
return this.audios.find(audio => false === audio.paused);
}
toggle(nextAudio) {
const currentAudio = this.getCurrentAudio();
if (currentAudio && currentAudio !== nextAudio) {
currentAudio.pause();
nextAudio.play();
}
nextAudio.paused ? nextAudio.play() : nextAudio.pause();
}
render() {
if (this.state.songs) {
return <div className="song-list">{this.state.songs}</div>;
} else {
return <div className="song-list"></div>;
}
}
}
export default AudioList;
我正在使用我在 Stackoverflow ( https://stackoverflow.com/a/50595639 )上找到的先前解决方案中的此代码。我能够实施此解决方案来解决我自己的挑战,即需要使用一个音频播放器和多个按钮拥有多个音频源。但是,我现在面临一个新的挑战 - 我希望在触发事件时更改特定按钮的文本。
我想出了这个实现,其中按钮文本基于名为 buttonText 的状态中的数组。按钮在启动时正确呈现,但是当事件侦听器拾取事件并更改状态时,按钮中的文本不会重新呈现或更改,即使它基于处于状态的数组中的元素在改变。
有没有人对为什么它可能无法重新渲染有任何建议?
编辑:更改状态中的单个数组元素基于React:how to update state.item[1] in state using setState?