我有一个进步的Web应用程序,它使用了带有历史包的react路由器进行导航。在特定的路线上,我想显示一个按钮,允许用户直接将产品安装到他们的设备上。按钮的显示侦听beforeinstallprompt事件。它将事件存储在状态中,并在用户按下按钮时触发事件,代码非常简单,如下所示:
import React from 'react';
import styled from 'styled-components';
import Button from 'components/common/button';
function InstallRoute() {
const [deferredPrompt, setDeferredPrompt] = React.useState(null);
const beforeInstallPrompt = (event) => {
event.preventDefault();
setDeferredPrompt(event);
};
React.useEffect(() => {
window.addEventListener('beforeinstallprompt', beforeInstallPrompt, true);
return () => {
window.removeEventListener('beforeinstallprompt', beforeInstallPrompt, true);
};
});
function install() {
if (!deferredPrompt) return;
deferredPrompt.prompt();
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
// accepted
} else {
// dismissed
}
setDeferredPrompt(null);
});
}
return (
<InstallWrapper visible={deferredPrompt !== null}>
<Button onClick={install}>Install app</Button>
</InstallWrapper>
);
}
const InstallWrapper = styled.div`
padding: 32px;
display: ${props => props.visible ? 'block' : 'none'};
`;
export default InstallRoute;然而,问题是beforeinstallprompt事件只在初始加载时触发。这意味着它只在刷新或使用window.location = '/installroute'导航到该路由时触发。使用history.push或NavLink从react路由器包导航到安装路由时,事件不会触发。
当刷新或硬位置更改时,安装按钮可以正常工作,但我很自然地希望它能够与react路由器/历史记录一起工作。我不想用肮脏的地点来污染这个项目。
有什么解决办法吗?我是否应该在安装路由时使用一种不同类型的路由元素,或者使用history.push的替代方法?
发布于 2022-02-25 02:28:56
尝试此事件=新事件(‘在安装前提示’)window.dispatchEvent(事件)
https://stackoverflow.com/questions/62674868
复制相似问题