【问题标题】:Why my particular useEffect hook didn't run when deps changed为什么我的特定 useEffect 钩子在 deps 更改时没有运行
【发布时间】: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


【解决方案1】:

你的钩子依赖只会在渲染组件时被评估。因此,您必须确保的第一件事是组件正在按照您的预期进行渲染。你可以在你的钩子之前用一个简单的console.log 来调试它。

您的问题很可能与钩子无关,而与 Redux 有关。也许你的 reducer 是直接设置 isPlaying 字段,而不是为新对象替换它的状态切片?

【讨论】:

  • 我在我的钩子之前添加了一个console.log('我正在渲染')并打印,这是否意味着它正在渲染?现在我将我的减速器添加到问题中,事情是当我更改 isPlaying 字段钩子工作以及 id 字段更改使第二个钩子工作,但是当我将两个部门添加到一个钩子时它不起作用,我不明白为什么
【解决方案2】:

useEffect(() => {

}, [primitiveTypeDeps])

当 deps 是一个对象/数组时,useEffect 函数不会检测到变化, 尝试使用原始值 -> 跟随

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

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

【讨论】:

  • 谢谢你的回答,emm我把里面的store去掉了,两个dep都是boolean和number,还是不行,我编辑问题也许你可以再检查一遍
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 2021-12-12
  • 2020-12-25
  • 1970-01-01
  • 2019-04-02
  • 2020-02-21
  • 2021-10-24
  • 2021-01-13
相关资源
最近更新 更多