【问题标题】:Use of useEffect with useLocation使用 useEffect 和 useLocation
【发布时间】:2021-04-01 10:41:57
【问题描述】:

我想知道使用(或不使用)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 将在组件安装后返回。我正在尝试了解成为更好程序员的最佳实践。

【问题讨论】:

    标签: javascript reactjs url use-effect


    【解决方案1】:

    useEffect 的原因是因为您在效果中设置了state。如果您删除 useEffect 并执行以下操作:

    const location = useLocation();
    const [currentPath, setCurrentPath] = useState('');
    
    setCurrentPath(location.pathname);
    

    你可能会看到这个错误:

    重新渲染过多。 React 限制渲染次数以防止无限循环。

    这是因为setCurrentPath 在每次渲染时运行,它会导致新的渲染,从而导致无限循环。

    useEffect 允许您在 deps 未更改时选择不执行某项操作。这里 setCurrentPath 仅在 location 更改时调用。

    但更广泛的一点是,您通常不需要在组件状态中“缓存”位置状态。它已经是 useLocation 钩子中的一个状态。只是阅读并使用它,不要存储它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-19
      • 2019-11-16
      • 2021-03-23
      • 2020-11-25
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2021-11-04
      相关资源
      最近更新 更多