【发布时间】:2020-07-06 03:30:56
【问题描述】:
我尝试控制我的应用程序在歌曲的播放/暂停中使用 redux 名称为 isPlaying 的状态,当我当前歌曲的 id 更改时,获取数据并调度操作以更改详细信息,我希望效果依赖于 isPlaying和id,所以当我换歌时播放没有停止,但是为什么我的id改变时这个效果不会运行。第一个钩子控制歌曲播放,第二个控制歌曲的详细信息获取,第二个钩子可以运行,但第一个不能。
useEffect(() => {
const audio = document.getElementById('audioSource');
state.playerControl.isPlaying? audio.play():audio.pause()
},[state.playerControl.isPlaying,store,state.playerViews.currentSongStatus.id])
useEffect( () => {
fetch(`http://localhost:5000/api/songsResourceObjArr/${store.getState().playerViews.currentSongStatus.id}`,{
mode:'cors',
header:{
'Access-Control-Allow-Origin':'*'
}
})
.then(
(res) => res.text()
)
.then(
(data) => {
console.log(data)
store.dispatch({type:'changeCurrentSongStatus',
payload:JSON.parse(data)[0]})
}
)
} , [state.playerViews.currentSongStatus.id, store])
case 'changePlayingStatus':
return{
...state,
isPlaying:!state.isPlaying
}
加: 我这样说就可以了
useEffect(() => {
const audio = document.getElementById('audioSource');
state.playerControl.isPlaying? audio.play():audio.pause()
},[state.playerControl.isPlaying])
useEffect( () => {
fetch(`http://localhost:5000/api/songsResourceObjArr/${store.getState().playerViews.currentSongStatus.id}`,{
mode:'cors',
header:{
'Access-Control-Allow-Origin':'*'
}
})
.then(
(res) => res.text()
)
.then(
(data) => {
console.log(data)
store.dispatch({type:'changeCurrentSongStatus',
payload:JSON.parse(data)[0]})
const audio = document.getElementById('audioSource');
store.getState().playerControl.isPlaying? audio.play():audio.pause()
}
)
} , [state.playerViews.currentSongStatus.id])
所以这让我很困惑,为什么当我将两个 deps 放入 deps 数组时它不起作用?
【问题讨论】:
-
也许你可以在获取之前尝试调用停止功能。
-
store 对象不应该在 useEffect 数组 deps 中
标签: javascript reactjs redux react-hooks