e.prompt()派生于无限useEffect循环中的beforeinstallprompt原因。
在beforeinstallprompt上,handle_storePrompt()将showButton设置为true (<button /> "display:block")。OnClick,handle_prompt()将showButton设置为false (<button /> "display:none")。在解决了提示符()之后,beforeinstallprompt就会被触发,导致handle_storePrompt()再次运行。
组件
const [showButton, setShowButton] = useState(false)
const [prompt, setPrompt] = useState()
useEffect(() => {
const handle_storePrompt = e => {
e.preventDefault()
console.log('Action Triggered')
setPrompt(e)
setShowButton(true)
}
window.addEventListener('beforeinstallprompt', e =>
handle_storePrompt(e)
)
return _ => {
window.removeEventListener('beforeinstallprompt', e =>
handle_storePrompt(e)
)
}
}, [])
const handle_prompt = _ => {
setShowButton(false)
prompt.prompt()
}
return (
<button className={showButton ? Styles.show : ''} onClick={handle_prompt}>
<small>Click to Install</small>
</button>
)发布于 2020-07-25 07:38:02
我通过从setShowButton(true) ()中删除handle_storePrompt()并将showButton状态初始化为true来解决这个问题。
接下来,showButton可以使用本地存储日期变量初始化,以防止<button />显示每次访问/刷新。
const [showButton, setShowButton] = useState(true)
const [prompt, setPrompt] = useState()
useEffect(() => {
const handle_storePrompt = e => {
e.preventDefault()
if (showButton) setPrompt(e)
}
window.addEventListener('beforeinstallprompt', e =>
handle_storePrompt(e)
)
return _ => {
window.removeEventListener('beforeinstallprompt', e =>
handle_storePrompt(e)
)
}
}, [showButton])
const handle_prompt = _ => {
setShowButton(false)
prompt.prompt()
setPrompt(null)
}
return (
<button className={showButton ? Styles.show : ''} onClick={handle_prompt}>
<small>Click to Install</small>
</button>
)https://stackoverflow.com/questions/63084200
复制相似问题