我想知道使用(或不使用)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)...}Returnspathname: /results:CancercurrentPath: /results:Cancer我的意思是,我發現的唯一區別是,使用 useEffect 時,返回將在組件安裝后發生。我正在嘗試了解成為更好的程序員的最佳實踐。
將 useEffect 與 useLocation 一起使用
慕的地10843
2024-01-18 15:48:22