1

我目前在Cannot read property 'addEventListener' of undefined运行我的反应代码时遇到错误。该代码旨在遍历包含音频文件的列表并获取音频持续时间。该应用程序正确呈现,但我在生命周期中做错了什么。我认为。下面的代码

import React, { useRef, useEffect, useState } from "react"
import { Link } from "gatsby"

const Single = ({ name, tracks }) => {
  const [duration, setDuration] = useState([])
  const audioRef = useRef([])

  function getTrackLength(track) {
    track.addEventListener("loadedmetadata", function () {
      setDuration(track.duration)
    })
  }
  useEffect(() => {
    audioRef.current = new Array(tracks.length)
  }, [])
  useEffect(() => {
    if (audioRef.current.length !== 0) {
      for (let i = 0; i <= audioRef.current.length; i++) {
        getTrackLength(audioRef.current[i])
      }
    }
  }, [])
  return (
    <>
      <h2>{name}</h2>

      <ul>
        {tracks.map((track, i) => (
          <li key={track._id}>
            <div>
              <strong>{track.name}</strong>
              <audio
                ref={el => (audioRef.current[i] = el)}
                src={track.file}
                controls
              />
              <i>{duration}</i>
            </div>
          </li>
        ))}
      </ul>
      <Link to="/singles">Back</Link>
    </>
  )
}

export default Single

提前谢谢了

4

1 回答 1

0

您有一个额外的迭代,其中undefined包含track

//               v not <=
for (let i = 0; i < audioRef.current.length; i++) {
  getTrackLength(audioRef.current[i]);
}

您的组件应如下所示:

const Single = ({ name, tracks }) => {
  const [duration, setDuration] = useState([]);
  const audioRef = useRef(new Array(Number(tracks.length));

  useEffect(() => {
    function getTrackLength(track) {
      track.addEventListener("loadedmetadata", function () {
        setDuration([...duration, track.duration]);
      });
    }

    for (let i = 0; i < audioRef.current.length; i++) {
        getTrackLength(audioRef.current[i]);
    }
  }, []);

  return (
    <>
      <h2>{name}</h2>
      <ul>
        {tracks.map((track, i) => (
          <li key={track._id}>
            <div>
              <strong>{track.name}</strong>
              <audio
                ref={(el) => (audioRef.current[i] = el)}
                src={track.file}
                controls
              />
              <i>{duration[i]}</i>
            </div>
          </li>
        ))}
      </ul>
      <Link to="/singles">Back</Link>
    </>
  );
};

export default Single;

于 2020-06-09T18:11:09.467 回答