首页 > 解决方案 > 为什么我的特定 useEffect 钩子在 deps 更改时没有运行

问题描述

我尝试使用 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 数组时它不起作用?

标签: javascriptreactjsreduxreact-hooks

解决方案


使用效果(()=> {

}, [primitiveTypeDeps])

当 deps 是对象/数组时,useEffect 函数不会检测到更改,请尝试使用原始值 -> 以下

这是原始数据类型 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

那么为什么需要将原始数据类型放入 useEffect deps array 原始类型不保留引用并且 useEffect 可以轻松检查值是否已更改


推荐阅读