React - проигрывать медиа после загрузки элементов с помощью array.map () - PullRequest
0 голосов
/ 11 ноября 2019

Я использую Reaction-Player для рендеринга видео YouTube с map(), например так:

class Jukebox extends Component {
  constructor (props) {
    super(props);
    this.state = {
     youtube_urls:[],      
     clients:[],        
    };
  };

  componentDidMount() {
    if (this.props.isAuthenticated) {
      this.getItems();
    }
  };

  getItems(event) {
    const {userId} = this.props
    const options = {
      url: `${process.env.REACT_APP_WEB_SERVICE_URL}/jukebox/${userId}`,
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': true,
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    };
    return axios(options)
    .then((res) => { 
      console.log(res.data)  
      console.log(res.data.data) 
      this.setState({
        clients: res.data.data[0].clients,
        youtube_urls:res.data.data[0].youtube_urls
      })
    })
    .catch((error) => { console.log(error); });
  };

render() {
 const { youtube_urls } = this.state;
 return (
  <div>      
   <h1 className="title is-1">Jukebox</font></h1>
  {
   clients.map((client, index) => {
     /* 
    Obtain preview from state.previews for current artist index 
    */
    const audio = youtube_urls[index]
    /* 
    Render current client data, and corresponding audio url
    */
    return(
      <div key={index}>
      <ul>
        <ReactPlayer 
          url={ audio }
          controls
          playing // <--- does not work
          width='50'
          height='150'
        />
        <div className="Line" />
      </ul></div>
     )
   })
 })
};

По словам одного из реквизитов библиотеки, playing (см. выше), вы можете автоматически воспроизводить мультимедиа по окончании рендеринга, но если я использую map(), это приведет к одновременному воспроизведению всех видео.

В то же время, существует обратный вызов onReady():

Вызывается, когда носитель загружен и готов к воспроизведению. Если для воспроизведения задано значение true, мультимедиа будет воспроизводиться немедленно.


ВОПРОС:

Как реализовать это и воспроизвести все видео, начиная синдекс 0 включен, по одному за раз, после загрузки всех носителей?

1 Ответ

1 голос
/ 11 ноября 2019

Я бы использовал две переменные состояния: videosLoadedCount, playingIndex. Инициализируйте videosLoadedCount в 0 и playingIndex в -1.

Вы можете вывести игровые реквизиты из значения состояния playingIndex.

Когда есть onReady, увеличивайте videosLoadedCount. Когда он достигнет количества видео, вы можете увеличить playingIndex. Всякий раз, когда есть обратный вызов onEnded, вы увеличиваете playingIndex.


Примерно так должно работать:

class Jukebox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loadedVideosCount: 0,
      currentPlayingIndex: -1,
    };
  }

  render() {
    const { youtube_urls } = this.props;
    const { loadedVideosCount, currentPlayingIndex } = this.state;

    return (
      <div>
        {youtube_urls.map((url, index) => (
          <ReactPlayer
            url={url}
            controls
            onLoaded={() =>
              this.setState(currentState => ({
                loadedVideosCount: loadedVideosCount + 1,
                currentPlayingIndex:
                  loadedVideosCount + 1 === youtube_urls.length ? 0 : -1,
              }))
            }
            onEnded={() =>
              this.setState(currentState => ({
                currentPlayingIndex: currentPlayingIndex + 1,
              }))
            }
            playing={index === currentPlayingIndex} // <--- does not work
            width="50"
            height="150"
          />
        ))}
      </div>
    );
  }
}
...