【发布时间】:2020-08-06 02:46:58
【问题描述】:
我正在尝试在 React 中呈现音频播放器的播放列表信息。数据来自父组件 (PostContent.js) 中的 fetch 调用。返回的数据是一个对象数组,如下所示: [ {name: 'track name', artist: '艺术家名', url: 'https://blahblah.wav', lrc: 'string', theme: 'another string' }, {...}, {...} 等 }
我无法在子组件 (AudioPlayer.js) 的 render() 方法中返回数据。当我在 render() 中使用 console.log(this.props.audio) 时,我的终端会打印三个响应。第一个是空数组,接下来的两个是我需要的正确数据(对象数组)。
如何在 AudioPlayer.js 组件的 render() 方法中的“props”对象中的“audio”键上设置 props?
我应该提到我正在使用 react-aplayer 库,并且我可以使用硬编码数据来完成这项工作,如此处的示例 (https://github.com/MoePlayer/react-aplayer),但我正在尝试制作一个动态播放列表博客网站的组件。非常感谢任何建议。
AudioPlayer.js(子组件)
import React, { PureComponent, Fragment } from 'react';
import ReactAplayer from '../react-aplayer';
import './AudioPlayer.css';
import sample from '../../src/adrian_trinkhaus.jpeg';
export default class AudioPlayer extends React.Component {
// event binding example
onPlay = () => {
console.log('on play');
};
onPause = () => {
console.log('on pause');
};
// example of access aplayer instance
onInit = ap => {
this.ap = ap;
};
render() {
console.log('props in render of AudioPlayer', this.props.audio)
const props = {
theme: '#F57F17',
lrcType: 3,
audio: this.props.audio
};
return (
<div>
<ReactAplayer
{...props}
onInit={this.onInit}
onPlay={this.onPlay}
onPause={this.onPause}
/>
</div>
);
}
}
PostContent.js(父组件)
import React, { Component, useState, Fragment } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import AudioPlayer from './AudioPlayer';
export default class PostContent extends Component {
constructor(props) {
super(props);
this.state = {
id: '',
episodeData: [],
audio: []
}
}
async componentDidMount() {
const { id } = this.props.match.params;
const response = await fetch(`http://localhost:5000/episode/${id}/playlist`);
const jsonData = await response.json();
const songs = jsonData;
const audio = Object.keys(songs).map(key => {
return {
name: songs[key].name,
artist: songs[key].artist,
url: songs[key].url,
cover: songs[key].cover,
lrc: songs[key].lrc,
theme: songs[key].theme
}
});
this.setState({ audio })
}
componentDidUpdate(prevProps, prevState) {
if (prevState.audio !== this.state.audio) {
const newAudio = this.state.audio;
this.setState({ audio: newAudio }, () => console.log('new audio', this.state.audio))
}
}
render() {
return (
<Fragment>
<AudioPlayer audio={this.state.audio} />
<Link id='home-link' to='/' activeClassName='active'>Homepage</Link>
{this.state.episodeData.map((item, i) => (
<div key={i} className="word-content">
<h2 className="show-title">{item.post_title}</h2>
<div className="episode-post-content">
<p>{item.post_content1}</p>
<p>{item.post_content2}</p>
<p>{item.post_content3}</p></div>
</div>
))}
<Table data={this.state.data} />
<div className="bottom-link">
<Link id='home-link' to='/' activeClassName='active'>Homepage</Link>
</div>
</Fragment>
)
}
}
【问题讨论】:
标签: javascript reactjs