【发布时间】:2021-08-05 13:29:33
【问题描述】:
我目前正在使用 Reactjs,由于某种原因,在 Safari 浏览器上按下后退/前进按钮时,我遇到了状态管理问题,它使组件与以前完全相同,但 URL 会更新。
注意:在 iPhone 上滑动时也会发生这种情况。
我可以通过以下方式解决此问题:
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
我正在寻找一个不同的解决方案,因为这似乎很麻烦,并且会进行轻微的双重刷新,并且在发生时很明显。
用于路由器的库:react-router-dom
React Dom 渲染:
ReactDOM.render(
<AuthProvider>
<IntercomProvider autoBoot={true} appId={''}>
<App />
</IntercomProvider>
</AuthProvider>,
document.getElementById('root')
);
交换机路由:
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
export default function App() {
return (
<React.Suspense fallback={<span>Loading...</span>}>
<Router>
<ReactNotification />
<React.StrictMode>
<Switch>
<Route exact path="/" component={Home} />
{singleRouting.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} />
))}
{boilerAdviceRouting.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} />
))}
{boilerQuotesRouting.map((route, i) => (
<RouteWithSubRoutes key={i} {...route} />
))}
<Route path="*">
<Error />
</Route>
</Switch>
<GoogleAnalyticsLocation />
</React.StrictMode>
</Router>
</React.Suspense>
);
}
const RouteWithSubRoutes = (route) => {
return (
<Route
exact={route.exact || undefined}
path={route.path}
render={(props) => (
// pass the sub-routes down to keep nesting
<route.component {...props} />
)}
/>
);
}
更新:
经过研究,除了刷新页面,我找不到任何解决方案。我必须在页面被重定向之前向所有操作按钮添加回调以重置状态,这不是最好的解决方案,但至少在有人提出实际答案之前解决。
【问题讨论】:
-
你能分享一些你的路由发生在哪里的代码吗?
-
@sschwei1 已更新
-
@sschwei1 - 只有当您按下浏览器的返回按钮时才会发生这种情况,如果您使用
a标签重定向就可以了 -
@GiovanniEsposito - 我已将路由器更改为 react-router-dom ,这是同样的问题。有什么想法吗?
-
能否包含
import/Router、Switch、Route的定义?
标签: javascript reactjs react-router-dom