【问题标题】:this.props Not Returning Fetched Data From Parent Component (React)this.props 不返回从父组件获取的数据(反应)
【发布时间】: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


    【解决方案1】:

    我在codesandbox 上使用您的代码玩了一个异步场景

    我认为问题在于,当您尝试访问 ReactAPlayer 组件中的有效负载时,音频尚未从异步调用中加载。您需要做的就是仅在有效时使用“音频”,例如 if (audio.length) {...}audio &amp;&amp; ... 某种形式的检查以防止它在 reactAplayer 渲染函数中被访问。

    fyi - 你可以删除 componentDidUpdate 钩子,因为你在 ...Didmount 钩子中有一个 setState 调用,当在 ...didMount 内部调用 setState 时,组件调用它的 render() 因此触发一个孩子重新渲染,它的孩子也会做同样的事情..

    【讨论】:

    • 非常感谢!我在 组件周围放置了一个条件运算符,就成功了。所以它看起来像: {props.audio.length > 0 ?

      没有数据

      }。再次感谢您的帮助 - 我整天都在努力解决这个问题!
    【解决方案2】:

    实际上我认为它不起作用,因为您将 this.props 设置在 props 对象中,所以也许您需要执行类似的操作

    var that = this 
    const props = {
      audio = that.props.audio 
    }
    

    【讨论】:

    • 哦,很好。感谢那!我把它放进去,但看起来它可能是来自获取的数据的问题。当我在 return() 上方 console.log(props) 时,我得到三个响应。第一个响应不包括音频键/值。接下来的两个确实包括它们。有没有办法确保在渲染返回之前在音频键上设置了道具?
    猜你喜欢
    • 2019-05-18
    • 2018-03-07
    • 2020-02-04
    • 2021-01-26
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多