Jon*_*ler 8 javascript url reactjs use-effect
我想知道使用(或不使用)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)
...
}
Run Code Online (Sandbox Code Playgroud)
Returns
pathname: /results:Cancer
currentPath: /results:Cancer
Run Code Online (Sandbox Code Playgroud)
我的意思是,我发现的唯一区别是,使用 useEffect 时,返回将在组件安装后发生。我正在尝试了解成为更好的程序员的最佳实践。
此处的原因useEffect是因为您正在设置state效果内。如果您删除useEffect并执行以下操作:
const location = useLocation();
const [currentPath, setCurrentPath] = useState('');
setCurrentPath(location.pathname);
Run Code Online (Sandbox Code Playgroud)
您可能会看到此错误:
重新渲染次数过多。React 限制渲染数量以防止无限循环。
这是因为它setCurrentPath在每个渲染上运行并导致新的渲染,从而导致无限循环。
useEffectdeps允许您在未更改时选择不执行某些操作。这里setCurrentPath仅当location更改时才调用。
但更广泛的一点是,您通常不需要在组件状态中“缓存”位置状态。已经是陷入困境的状态了useLocation。只需阅读并使用它,不要存储它。