admin管理员组文章数量:1129293
I can see in this file (.13.3/modules/createRouter.js) that there is a refresh function but I have no idea how to call it. I'm fairly new to react-router, I've only used it to move between some pages a couple times using hashHistory.
Right now I am trying to use it so that when an install fails, the user is given the option to 'retry' which I plan to execute by refreshing the page where the install happens (the page the user would be currently on). Any help would be appreciated.
This is a node app that runs on electron, not a web app.
I can see in this file (https://github.com/ReactTraining/react-router/blob/v0.13.3/modules/createRouter.js) that there is a refresh function but I have no idea how to call it. I'm fairly new to react-router, I've only used it to move between some pages a couple times using hashHistory.
Right now I am trying to use it so that when an install fails, the user is given the option to 'retry' which I plan to execute by refreshing the page where the install happens (the page the user would be currently on). Any help would be appreciated.
This is a node app that runs on electron, not a web app.
Share Improve this question edited Oct 19, 2017 at 0:09 Austin Greco 33.5k6 gold badges59 silver badges61 bronze badges asked Oct 18, 2017 at 23:24 SheriffSheriff 1,1872 gold badges9 silver badges10 bronze badges25 Answers
Reset to default 138firstly, add react-router as a dependency
yarn add react-router
or npm install react-router
Then (for 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)
This causes your page to re-render automatically
For react-router v6 use the useNavigate
hook instead:
import { useNavigate } from 'react-router'
const navigate = useNavigate()
// refresh
navigate(0)
If you're using react-router v6
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
const refreshPage = () => {
navigate(0);
}
You can use this to refresh Current route:
import createHistory from 'history/createBrowserHistory'
const history = createHistory();
history.go(0)
You don't really need react-router
for this. You can just use location.reload
:
location.reload();
Also that version of react-router you linked to is very old, I think it's linking to v1 when it's currently on v4.
React
window.location.reload();
working
if you want to re-fetch the data just do the below:
import { useLocation } from 'react-router'
const location = useLocation()
useEffect(() => {
fetchData()
}, [location.key])
I guess that you're using react-router. I'll copy my answer from another post. So you have few possibilities to do that, currently my favorite way to do that is using anonymous function in component prop:
<Switch>
<Route exact path="/" component={()=><HomeContainer/>} />
<Route exact path="/file/:itemPath/:refHash" component={()=><File/>} />
<Route exact path="/:folderName" component ={()=><Folder/>}/>
</Switch>
Or if you want to refresh with current url params, you'll need extra route (reload), and play a little with router stack:
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>
I know that this is old, but I found a simple solution according to the documentation of react-router.
Just put that attribute on your Router, and whenever you are on a new Path it will force the page to reload itself.
<Router forceRefresh={true}>
Source: https://reactrouter.com/web/api/BrowserRouter/forcerefresh-bool
This solution won't cause the undesired full page reload but requires you to make this modification to each page that needs refreshing:
export const Page = () => {
const location = useLocation();
return <PageImpl key={location.key} />
}
So the idea is: create a wrapper around your page and make React re-create the actual page every time the location key changes.
Now it's enough to call history.push(/this-page-route)
again and the page refreshes.
With React Router 6 you can simply write :
import {useNavigate} from "react-router-dom";
const navigate = useNavigate()
const goToPageOnClick = () =>{
navigate(target_url)
navigate(0)
}
If you want to use <Link/>
to reload some route, or simply have single history push, you can setup <Redirect/>
route under <Switch/>
like this:
<Switch>
<Route exact path="/some-route" component={SomeRoute} />
<Redirect exact from="/some-route/reload" to="/some-route" />
</Switch>
And then <Link to="/some-route/reload" />
or push("/some-route/reload")
If you don't want to reload all scripts again you can replace the current path with a fake/empty path and replace it again with the current path like this
// ...
let currentPath = window.location.pathname;
history.replace('/your-empty-route');
setTimeout(() => {
history.replace(currentPath)
}, 0)
// ...
Update:
If the changing of the address bar bothering, you can add a patterned route like this:
<Route path="/*/reload" component={null}/>
and add /replace
to the end of currentPath
to replace the router with null component. like this:
// ...
let currentPath = window.location.pathname;
history.replace(`${currentPath}/replace`);
setTimeout(() => {
history.replace(currentPath)
}, 0)
// ...
In this way, the reload
keyword will add to the end of your current path and I think it's more user friendly.
Notice: If you already have a route that ends with replace It will cause conflict. To solve that you should change the path of the patterned route to something else.
You could try this workaround:
// I just wanted to reload a /messages page
history.pushState(null, '/');
history.pushState(null, '/messages');
You can use this function.
function reloadPage(){
window.location.reload();
}
<input type="button" onClick={ reloadPage } value="reload"/>
May be you are trying to push in history object, then bind your component with withrouter
or use window.location.href = url
to redirect ..
You can achieve that with React Router v6.
import React from 'react';
import { useNavigation, useLocation } from 'react-router-dom';
const Component = () => {
const navigate = useNavigation();
const location = useLocation();
const reload = () => {
navigate(location.pathname);
};
return (
...
);
};
and then put your reload function inside a useEffect hook like this.
useEffect(()=>{
reload();
},[navigate, location])
PS: but this is a weird question, since react-router reloads the page automatically.
If you are needing an asynchronous reload, use history.go(0)
(it wraps the History.go() method).
If you need to reload the page synchronously, use history.push(location.pathname)
(it wraps the History.pushState() method).
Since there are already examples here using history.go(0)
, here's an example using history.push(location.pathname)
:
import React from 'react';
import { useHistory, useLocation } from 'react-router-dom';
const Component = () => {
const history = useHistory();
const location = useLocation();
const reload = () => {
history.push(location.pathname);
};
return (
...
);
};
Looking at all the answers to this question they all seem to do a hard refresh of the page or worked on a specific page. I was looking to do a softer sort of refresh to the page and make a component that can do this on any page. The way I ended up implementing it was to redirect the user to a view that doesn't exist and then going back to the previous page.
using react-router-dom
import {useNavigate} from "react-router-dom";
const RefreshButton= ()=>{
const navigate = useNavigate()
const softRefreshPage = () =>{
// visit page that doesn't exist
navigate("/refresh");
navigate(-1);
}
return <button onClick={softRefreshPage}>refresh</button>
}
Clicking the button in this example will redirect you to the /refresh page then back. This will force the components on the current view to re render. Note a side effect of this is that the user may see a blank page for a second. You can make a page at the /refresh route that will just show a loading icon which can be more user friendly.
Here is a custom hook for reloading the page without hard refreshing and keeping search params as well :
// useReloadPage.js
export function useReloadPage() {
const navigate = useNavigate();
const location = useLocation();
return () => navigate(`${location.pathname}${location.search}`);
}
In my case, I use that custom hook on tanstack's useMutation
's onSuccess
object :
export function useDeleteQuestion(id) {
const queryClient = useQueryClient();
const reload = useReloadPage();
const { isLoading: isDeleting, mutate: deleteQuestion } = useMutation({
mutationFn: () => deleteQuestionApi(id),
onSuccess: () => {
queryClient.removeQueries({
// ...
})
reload();
},
});
return { isDeleting, deleteQuestion };
}
Here is my way of doing it in react-router-dom v5
without hard-refreshing and keeping search params and state create a separate component ReloadRoute
and pass the current page location as a state to the component
const ReloadRoute = () => {
const location = useLocation();
const { from } = location.state || {};
if (!from) {
return <Redirect to="/" />;
}
return (
<Redirect
to={{
pathname: from.pathname,
search: from.search,
state: from.state,
}}
/>
);
};
In routes add a route /reload
<Router history={history} basename={process.env.REACT_APP_BASENAME || ''}>
...
...
<Route path="/reload" component={() => <ReloadRoute />} />
</Router>
Then to trigger a reload of the current page
const SomeComponent = (props) => {
const location = useLocation();
const history = useHistory();
...
...
const handleOnButtonClick = () => {
history.replace(`/reload`, { from: location });
};
...
...
};
Just create page that will redirect to target page on mount. Here is example using router 5.
// This page helps to redirect to my target page even
// when current page already target.
// React-router doesn't support refresh page.
import React from 'react'
class TargetPageRedirect extends React.Component {
componentDidMount() {
this.props.history.push('/target-page')
}
render() {
return null
}
}
export default TargetPageRedirect
// In your router file
...
<Route path='/target-page' component={TargetPage} exact={true} />
<Route path='/target-page-redirect' component={TargetPageRedirect} exact={true} />
...
// In some other component
this.props.history.push('/target-page-redirect')
update webpacker.yml
devServer: {
historyApiFallback: true,
}
Well, the easiest way is to first identify a route for reload and thereafter call the window.location.reload()
function on the route like so:
<Switch>
<Route exact exact path="/" component={SomeComponent} />
<Route path="/reload" render= {(props)=>window.location.reload()} />
</Switch>
Just Write following Code for Refresh :
window.location.reload();
I recently had the same problem and created this(https://github.com/skt-t1-byungi/react-router-refreshable).
<Refreshable>
<Switch>
<Route path="/home">
<HomePage />
</Route>
<Route path="/post">
<PostPage />
</Route>
{/* ... */}
</Switch>
</Refreshable>
本文标签: javascriptHow do I reload a page with reactrouterStack Overflow
版权声明:本文标题:javascript - How do I reload a page with react-router? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736740560a1950489.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论