我目前在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
提前谢谢了