【发布时间】: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