英文:
Back Button doesn't fire useEffect with location as dependency
问题
On pressing back button of browser the useEffect
doesn't fire although the location is being changed. Redirecting url using window.open() doesn't fire a change in this useEffect once I press back button and return to page from where I was redirected.
const location = useLocation();
useEffect(() => {
// something that needs to run when there is a change in url
}, [location.pathname])
window.open(someUrl,"_self");
Things happening after window.open
- I am using SAML method to authenticate hence it redirects to a 3rd party server on logout
- Multiple redirects happen once 3rd party receives the logout request
- Once the logout is successful, I am redirected to my site from the server.
英文:
On pressing back button of browser the useEffect
doesn't fire although the location is being changed. Redirecting url using window.open() doesn't fire a change in this useEffect once I press back button and return to page from where I was redirected.
const location = useLocation();
useEffect(() => {
// something that needs to run when there is a change in url
}, [location.pathname])
window.open(someUrl,"_self");
Things happening after window.open
- I am using SAML method to authenticate hence it redirects to a 3rd party server on logout
- Multiple redirects happen once 3rd party receives the logout request
- Once the logout is successful, I am redirected to my site from the server.
答案1
得分: 2
useLocation
钩子返回一个Location
对象,具有以下接口:
export interface Path {
pathname: string;
search: string;
hash: string;
}
export interface Location extends Path {
state: any;
key: string;
}
没有path
属性。useEffect
钩子应该使用location.pathname
作为依赖项。
const location = useLocation();
useEffect(() => {
// 需要在URL路径变化时运行的一些操作
}, [location.pathname]);
或者
const { pathname } = useLocation();
useEffect(() => {
// 需要在URL路径变化时运行的一些操作
}, [pathname]);
演示
<details>
<summary>英文:</summary>
The `useLocation` hook returns a `Location` object with the following interface ([source][1]):
```typescript
export interface Path {
pathname: string;
search: string;
hash: string;
}
export interface Location extends Path {
state: any;
key: string;
}
There is no path
property. The useEffect
hook should use location.pathname
as the dependency.
const location = useLocation();
useEffect(() => {
// something that needs to run when there is a change in url path
}, [location.pathname]);
or
const { pathname } = useLocation();
useEffect(() => {
// something that needs to run when there is a change in url path
}, [pathname]);
Demo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论