javascript - 为什么我的特定 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 数组时它不起作用?
解决方案
使用效果(()=> {
}, [primitiveTypeDeps])
当 deps 是对象/数组时,useEffect 函数不会检测到更改,请尝试使用原始值 -> 以下
这是原始数据类型 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
那么为什么需要将原始数据类型放入 useEffect deps array 原始类型不保留引用并且 useEffect 可以轻松检查值是否已更改
推荐阅读
- python - pysyft torch.jit. 脚本 RuntimeError:未定义的值 _Reduction
- git - gitlab让加密http_authorization错误
- python - Python 找不到某些 Windows 可执行文件
- php - 是否有解决方案可以使用我添加的数据库中的选择选项重定向页面,并添加输入字段?
- c++ - C++ 中项目的 Xcode 11 完成行为
- python-3.x - 使用 BeautifulSoup 时迭代失败
- javascript - BsMultiSelect 和 jQuery 验证兼容性
- computer-science - -120 的补码表示是什么?
- ubuntu - snmpwalk:未知用户名 (SNMP v3)
- c - 使用 systemd 作为服务运行时从保存的代码中下载的文件在哪里