Reactjs 在Safari上单击后退按钮时使用React钩子强制重新加载页面
我想强制重新加载页面(即使在使用“后退”按钮导航时),因为在Safari浏览器中,Safari将加载页面的缓存版本,这不是我们想要的 使用React钩子,我可以在Reactjs 在Safari上单击后退按钮时使用React钩子强制重新加载页面,reactjs,safari,Reactjs,Safari,我想强制重新加载页面(即使在使用“后退”按钮导航时),因为在Safari浏览器中,Safari将加载页面的缓存版本,这不是我们想要的 使用React钩子,我可以在useffect中执行此操作 function MyComponent() { useEffect(() => { if (typeof window != 'undefined') { window.onpageshow = event => {
useffect
中执行此操作
function MyComponent() {
useEffect(() => {
if (typeof window != 'undefined') {
window.onpageshow = event => {
if (event.persisted) {
window.location.reload()
}
}
}
}, [])
return (<div>My Page Content</div>)
}
但我还是有同样的问题。强制重新加载是否会让我陷入这样一种情况:组件不断地被重新渲染、重新安装,并且重新加载被反复调用
最后,我希望在Safari上单击“上一步”按钮时,重新加载上一页,而不仅仅是从缓存中提取。是的,在这两种情况下,如果组件在启动时呈现,我希望页面进入无限循环重新加载页面 React钩子没有任何类型的持久性:它们对您创建的组件实例是有状态的,并且在组件卸载(或页面卸载)时它会被完全删除 作为建议,我认为您不需要在React组件中执行此操作。。。这只是一个你想时不时运行的脚本 此脚本的实现可以是您想要的任何内容,但我想到了两个示例:
if(!window.localStorage.getItem('is-refresh')) {
window.onpageshow = event => {
if (event.persisted) {
window.localStorage.setItem('is-refresh', true);
window.location.reload();
}
}
} else {
window.localStorage.removeItem('is-refresh');
}
这将始终只刷新页面一次。或者您可以使用时间戳:
const lastUpdate = window.localStorage.getItem('lastUpdate')
const lastUpdateTs = lastUpdate ? Number(lastUpdate) : 0;
if(Date.now() > lastUpdateTs + 3600) {
window.onpageshow = event => {
if (event.persisted) {
window.localStorage.set('lastUpdate', Date.now());
window.location.reload();
}
}
}
(当然,您也可以将其粘贴到useEffect中……但是否有任何原因需要在重新加载之前等待React完成渲染?这是否回答了您的问题?
const lastUpdate = window.localStorage.getItem('lastUpdate')
const lastUpdateTs = lastUpdate ? Number(lastUpdate) : 0;
if(Date.now() > lastUpdateTs + 3600) {
window.onpageshow = event => {
if (event.persisted) {
window.localStorage.set('lastUpdate', Date.now());
window.location.reload();
}
}
}