我想知道使用(或不使用)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 将在组件安装后返回。我试图了解成为更好程序员的最佳实践。
最佳答案
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
允许您在 deps
时选择不做某事没有改变。这里 setCurrentPath
仅在 location
时调用被改变。但更广泛的一点是,您通常不需要在组件状态中“缓存”位置状态。它已经是
useLocation
中的一个状态。钩。只需阅读并使用它,不要存储它。
关于javascript - 使用 useEffect 和 useLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65413590/