【问题标题】:"beforeinstallprompt" prompt() causes infinite useEffect loop"beforeinstallprompt" prompt() 导致无限 useEffect 循环
【发布时间】:2020-11-14 22:43:48
【问题描述】:

e.prompt() 派生自 beforeinstallprompt 导致无限 useEffect 循环。

beforeinstallprompt 上,handle_storePrompt()showButton 设置为 true (<button /> "display:block")。 OnClick,handle_prompt()showButton 设置为 false (<button /> "display:none")。在 prompt() 解决后,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>
)

【问题讨论】:

    标签: reactjs react-hooks progressive-web-apps gatsby


    【解决方案1】:

    我通过从 handle_storePrompt() 中删除 setShowButton(true) 并将 showButton 状态初始化为 true 解决了这个问题。

    接下来,showButton 可以使用本地存储日期变量进行初始化,以防止 &lt;button /&gt; 显示每次访问/刷新。

    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>
    )
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2020-11-16
      • 2021-11-01
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多