如何解决上下文API history.listen无法读取未定义的属性“ listen”
我正在使用具有浏览器历史记录PUSH和POP状态的React挂钩上下文API。当前收到此错误Cannot read property 'listen' of undefined
。如果我将浏览器历史记录功能移至另一个组件,则它可以完美运行且没有错误。我没有在下面的代码中包含所有状态。任何帮助都将非常棒,谢谢大家……
import React,{ useState,createContext,useEffect } from 'react'
import { useHistory } from 'react-router-dom'
const history = useHistory()
const [keys,setKeys] = useState([])
useEffect(() => {
return history.listen(location => {
if (history.action === 'PUSH') {
setKeys([location.key])
}
if (history.action === 'POP') {
if (keys[1] === location.key) {
setKeys(([ _,...keys ]) => keys)
setPage(page + 1)
setCount(count + 1)
setPercentage(percentage + 20)
} else {
setKeys((keys) => [ location.key,...keys ])
setPage(page - 1)
setCount(count - 1)
setPercentage(percentage - 20)
}
}
})
},[keys,count,percentage])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。