现在我想在安装失败时使用它,让用户可以选择“重试”,我打算通过刷新正在进行安装的页面(用户当前所在的页面)来执行此操作。任何帮助将不胜感激。
这是一个在electron上运行的node应用程序,而不是web应用程序。
现在我想在安装失败时使用它,让用户可以选择“重试”,我打算通过刷新正在进行安装的页面(用户当前所在的页面)来执行此操作。任何帮助将不胜感激。
这是一个在electron上运行的node应用程序,而不是web应用程序。
首先,将react-router添加为依赖项
yarn add react-router
或 npm install react-router
然后(针对react-router v5)
import { useHistory } from 'react-router'
const history = useHistory()
// then add this to the function that is called for re-rendering
history.go(0)
这会导致您的页面自动重新渲染。
对于 react-router v6,请改用 useNavigate
hook:
import { useNavigate } from 'react-router'
const navigate = useNavigate()
// refresh
navigate(0)
如果你正在使用 react-router v6
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
const refreshPage = () => {
navigate(0);
}
导航("/");
导航(0);
- bownie您可以使用此功能刷新当前路由:
import createHistory from 'history/createBrowserHistory'
const history = createHistory();
history.go(0)
其实您不需要使用react-router
,只需使用location.reload
即可:
location.reload();
同时,你链接的那个react-router版本非常老,我认为它链接的是v1版本,而现在已经更新到了v4版本。
React
window.location.reload();
工作中
我猜你正在使用react-router。 我将复制我的另一篇文章中的答案。 所以你有几种可能的方法来做到这一点,目前我最喜欢的方法是在组件属性中使用匿名函数:
<Switch>
<Route exact path="/" component={()=><HomeContainer/>} />
<Route exact path="/file/:itemPath/:refHash" component={()=><File/>} />
<Route exact path="/:folderName" component ={()=><Folder/>}/>
</Switch>
如果您想使用当前的URL参数进行刷新,您需要添加额外的路由(reload),并对路由器堆栈进行微调。reload = ()=>{
const current = props.location.pathname;
this.props.history.replace(`/reload`);
setTimeout(() => {
this.props.history.replace(current);
});
}
<Switch>
<Route path="/reload" component={null} key="reload" />
<Route exact path="/" component={HomeContainer} />
<Route exact path="/file/:itemPath/:refHash" component={File} />
<Route exact path="/:folderName" component ={Folder}/>
</Switch>
<div onClick={this.reload}>Reload</div>
setTimeout
? - Dawson B如果您想重新获取数据,请按以下步骤操作:
import { useLocation } from 'react-router'
const location = useLocation()
useEffect(() => {
fetchData()
}, [location.key])
我知道这已经有些过时了,但我在react-router的文档中找到了一个简单的解决方案。
只需将该属性放在你的Router上,每当你在一个新的路径上时,它将强制页面重新加载自己。
<Router forceRefresh={true}>
Source: https://reactrouter.com/web/api/BrowserRouter/forcerefresh-bool
export const Page = () => {
const location = useLocation();
return <PageImpl key={location.key} />
}
这个想法是:创建一个包装器围绕您的页面,并使React每次更改位置键时重新创建实际页面。
现在只需再次调用history.push(/this-page-route)
,页面就会刷新。
如果你想使用<Link/>
重新加载某个路由,或者仅执行单一的历史记录推送,你可以像这样在<Switch/>
下设置<Redirect/>
路由:
<Switch>
<Route exact path="/some-route" component={SomeRoute} />
<Redirect exact from="/some-route/reload" to="/some-route" />
</Switch>
然后是 <Link to="/some-route/reload" />
或者 push("/some-route/reload")
history.go()
,我按预期注销并推送到登录屏幕。对于其他答案,我没有按预期工作。 - Lucas Reppe Welander