像‘window。location。pathname’这样的外部范围值不是有效的依赖项,因为改变它们不会重新渲染组件。用例 假设我们必须在每个页面上执行一个操作,并且每当路由更改时我们都必须执行此操作。 由于我们必须在每个页面组件上执行操作,所以让我们将逻辑抽象为一个钩子。文件 index。js文件包含具有两个页面的路由器配置主页和其他页面。 主页和其他页面仅呈现文本并调用公共useLocation挂钩。 在useLocation钩子中,我们将根据window。location。pathname执行一些操作,这是一个全局范围的变量。FILENAMEindex。jsimportRimport{render}import{BrowserRouterasRouter,Route,Link}importOtherfrom。componentsOimportHomefrom。componentsHBasicRoutertorenderHomePageandOtherPageconstBasicExample()(RouterulliLinktoHomeLinkliliLinktootherOtherLinkliulhrRouteexactpathcomponent{Home}Routepathothercomponent{Other}Router);render(BasicExample,document。getElementById(root));FILENAMEuseLocation。jsThisisthehookthatwewillberunningoneachpageimport{useEffect}constuseLocation(pathname){useEffect((){Ifthepathnameissameascurrentpagepath,performsomeoperationForthisexample,theoperationistoalerttheuseronlyifpathnamepassedandwindow。location。pathnameareequalif(pathnamewindow。location。pathname){alert(OnPage,pathname{pathname},window。location。pathname{window。location。pathname});}},〔pathname,window。location。pathname〕);};exportdefaultuseLHomePageimportRimportuseLocationfrom。。useLconstHome(){useLocation();returnh2Homeh2;};exportdefaultHOtherPageimportRimportuseLocationfrom。。useLconstOther(){useLocation(other);returnh2Otherh2;};exportdefaultO相互作用 在交互中,我们可以看到,一旦我们登陆主页,我们就会看到路径的警告,然后导航到其他页面,我们会看到路径other的警告。 一切似乎都很好,那么问题是什么?问题 让我们修改代码以在效果运行完成后执行清理操作。 在修改后的代码中,我们会将警报作为清理操作的一部分。FILENAMEuseLocation。jsThisisthehookthatwewillberunningoneachpageimport{useEffect}constuseLocation(pathname){useEffect((){Ifthepathnameissameascurrentpagepath,performsomeoperationForthisexample,theoperationistoalerttheuseronlyifpathnamepassedandwindow。location。pathnameareequalif(pathnamewindow。location。pathname){MODIFIEDCODEHEREremovedalertfromthisconditiondoSomeOperation()}MODIFIEDCODEHERECLEANUPOPERATIONAddedthesamealertherereturn(){alert(OnPage,pathname{pathname},window。location。pathname{window。location。pathname});}},〔pathname,window。location。pathname〕);};exportdefaultuseL 现在让我们看看交互 当我们导航到其他页面时,主页效果已经完成运行并运行清理操作。 虽然我们希望路径和路径名相同,但在警报中我们有路径名‘’和window。location。pathname‘other’。 发生这种情况是因为window。location。pathname在清理操作开始时发生了变化。 当我们从其他页面导航回主页时,也会发生同样的事情。解决方案 让我们修改代码以在依赖项中不使用window。location。pathname,而是使用钩子中定义的局部变量。FILENAMEuseLocation。jsThisisthehookthatwewillberunningoneachpageimport{useEffect}constuseLocation(pathname){MODIFIEDCODEHEREAssignedpathwindow。location。pathnameUsethisvariableacrossthehookconstpathwindow。location。useEffect((){Ifthepathnameissameascurrentpagepath,performsomeoperationForthisexample,theoperationistoalerttheuseronlyifpathnamepassedandpathareequalif(pathnamepath){doSomeOperation()}return(){alert(OnPage,pathname{pathname},window。location。pathname{path}Usepathinsteadofwindow。location。pathname);}},〔pathname,path〕);};exportdefaultuseL 现在让我们看看交互 应用修复后,我们可以看到我们获得了正确且一致的值。 这是可行的,因为路径是每个hook实例的局部变量。虽然它在初始化时被分配给window。location。pathname,但只有在重新渲染时才会重新分配。 你遇到过这样的问题吗!请在评论中让我知道!