【发布时间】:2022-11-13 17:07:28
【问题描述】:
我已经创建了一个音乐播放器作为我正在处理的项目的一部分,但我有这个错误。有没有人有办法解决吗?
[eslint] src\components\MusicPlayer.jsx 第 48:9 行:React Hook useEffect 缺少依赖项:'togglePlay'。要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps
我已经为这个例子缩短了代码。任何帮助,将不胜感激!
import React, { useState, useEffect, useRef } from 'react'
function MusicPlayer({songs}) {
//Test
const songFiles = songs.map(song => song.songFile)
//Hooks
const audioPlayer = useRef()
//State
const [index, setIndex] = useState(0);
const { songClicked} = useContext(songContext)
// setSongClicked
const [currentSong, setCurrentSong] = useState(songClicked);
const [isPlaying, setisPlaying] = useState(false);
const [volume, setVolume] = useState(30);
const [mute, setMute] = useState(false);
useEffect(() => {
setCurrentSong(songClicked)
if (songClicked) {
audioPlayer.current.play()
}
if (songClicked) {
togglePlay()
}
}, [songClicked])
useEffect(() => {
if(audioPlayer) {
audioPlayer.current.volume = volume / 100;
}
}, [volume]);
function togglePlay() {
if(!isPlaying) {
audioPlayer.current.play()
} else {
audioPlayer.current.pause()
}
setisPlaying(isPlaying => !isPlaying)
}
【问题讨论】:
-
您只需添加
// eslint-disable-next-line react-hooks/exhaustive-deps即可禁用该 lint。 -
我在哪里添加它?什么线?
-
就在依赖数组的上方。
-
@BikasLin 请避免建议其他人禁用 eslint。它的警告和错误大多是正确的。
标签: javascript reactjs