使用 useEffect 和 useLocation
Use of useEffect with useLocation
我想知道使用(或不使用)useEffect 来更新 useLocation 的最大区别是什么。
我通常发现人们在 useEffect 中设置 useLocation 以在 URL 的路径发生变化时更新状态,但我发现我不需要这样做来更新位置。
const NavBar = () => {
const location = useLocation();
const [currentPath, setCurrentPath] = useState('')
const location = useLocation();
console.log('pathname:', location.pathname)
useEffect(() => {
setCurrentPath(location.pathname);
}, [location]);
console.log('currentPath:', currentPath)
...
}
Returns
pathname: /results:Cancer
currentPath: /results:Cancer
我的意思是,我发现的唯一区别是使用 useEffect return 将在组件安装后发生。我正在努力了解成为更好程序员的最佳实践。
此处useEffect
的原因是因为您在效果中设置了state
。如果您删除 useEffect
并执行:
const location = useLocation();
const [currentPath, setCurrentPath] = useState('');
setCurrentPath(location.pathname);
您可能会看到此错误:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
这是因为 setCurrentPath
在每个渲染上运行,它会导致新的渲染,从而导致无限循环。
useEffect
允许您 opt-out 在 deps
没有改变的情况下做某事。这里 setCurrentPath
仅在 location
更改时调用。
但更广泛的一点是,您通常不需要在组件状态中“缓存”位置状态。它已经是 useLocation
挂钩中的一个状态。只看就用,不要收藏
我想知道使用(或不使用)useEffect 来更新 useLocation 的最大区别是什么。
我通常发现人们在 useEffect 中设置 useLocation 以在 URL 的路径发生变化时更新状态,但我发现我不需要这样做来更新位置。
const NavBar = () => {
const location = useLocation();
const [currentPath, setCurrentPath] = useState('')
const location = useLocation();
console.log('pathname:', location.pathname)
useEffect(() => {
setCurrentPath(location.pathname);
}, [location]);
console.log('currentPath:', currentPath)
...
}
Returns
pathname: /results:Cancer
currentPath: /results:Cancer
我的意思是,我发现的唯一区别是使用 useEffect return 将在组件安装后发生。我正在努力了解成为更好程序员的最佳实践。
此处useEffect
的原因是因为您在效果中设置了state
。如果您删除 useEffect
并执行:
const location = useLocation();
const [currentPath, setCurrentPath] = useState('');
setCurrentPath(location.pathname);
您可能会看到此错误:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
这是因为 setCurrentPath
在每个渲染上运行,它会导致新的渲染,从而导致无限循环。
useEffect
允许您 opt-out 在 deps
没有改变的情况下做某事。这里 setCurrentPath
仅在 location
更改时调用。
但更广泛的一点是,您通常不需要在组件状态中“缓存”位置状态。它已经是 useLocation
挂钩中的一个状态。只看就用,不要收藏