为什么useEffect不运行在window.location.pathname更改上?我只记录了一次loc。
当路径名更改而没有任何其他库时,如何运行useEffect?
useEffect(() => {
const loc = window.location.pathname
console.log({ loc })
}, [window.location.pathname])发布于 2019-10-18 02:18:46
创建一个钩子,类似于:
const useReactPath = () => {
const [path, setPath] = React.useState(window.location.pathname);
const listenToPopstate = () => {
const winPath = window.location.pathname;
setPath(winPath);
};
React.useEffect(() => {
window.addEventListener("popstate", listenToPopstate);
return () => {
window.removeEventListener("popstate", listenToPopstate);
};
}, []);
return path;
};然后在组件中像这样使用它:
const path = useReactPath();
React.useEffect(() => {
// do something when path changes ...
}, [path]);当然,您必须在顶层组件中这样做。
发布于 2022-03-30 11:39:07
奇怪的是,没有人提到这一点,但是,您可以使用react-router-dom钩子从useLocation获得位置。因此,您只需在依赖数组中使用它。
const location = useLocation();
useEffect(() => {
console.log(location);
}, [location.pathname]);发布于 2020-12-30 16:38:51
我调整了拉斐尔·莫拉的答案,使之适用于整个位置对象,并在Next.js应用程序的前端使用useIsMounted方法,并添加了类型记录类型。
hooks/useWindowLocation.ts
import useIsMounted from './useIsMounted'
import { useEffect, useState } from 'react'
const useWindowLocation = (): Location|void => {
const isMounted = useIsMounted()
const [location, setLocation] = useState<Location|void>(isMounted ? window.location : undefined)
useEffect(() => {
if (!isMounted) return
const setWindowLocation = () => {
setLocation(window.location)
}
if (!location) {
setWindowLocation()
}
window.addEventListener('popstate', setWindowLocation)
return () => {
window.removeEventListener('popstate', setWindowLocation)
}
}, [isMounted, location])
return location
}
export default useWindowLocationhooks/useIsMounted.ts
import { useState, useEffect } from 'react'
const useIsMounted = (): boolean => {
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(() => true)
}, [])
return isMounted
}
export default useIsMountedhttps://stackoverflow.com/questions/58442168
复制相似问题