无法在 React 中安装"useHistory"



我正在做一个谷歌克隆(迷你项目(,我需要从react-router-dom导入useHistory

我遵循了以下步骤:

步骤1:npm install --save react-router-dom(我在终端中使用了此命令(步骤2:import { useHistory } from "react-router-dom"(在我的文件顶部使用(步骤3:const history = useHistory()(在我的代码中使用这个(

在遵循这些步骤后,我得到了以下错误:

在中找不到导出"useHistory"(作为"useHistory"导入("react router dom"(可能的导出:AbortedDeferredError,Await,BrowserRouter,Form,HashRouter,Link,MemoryRouter,NavLink,Navigate,NavigationType,Outlet,Route,Router Provider,路由,滚动恢复,UNSAFE_DataRouterContext,UNSAFE_DataRouterStateContext、UNSAFE_DataSetaticRouterContext、,UNSAFE_LocationContext、UNSAFE_NavigationContext、UNSAF E_RouteContext,UNSAFE_enhanceManualRouteObjects,createBrowserRouter,createHashRouter,createMemoryRouter,创建路径,createRoutesFromChildren,createRoutesFrom Elements,createSearchParams,defer,generatePath,isRouteErrorResponse,json,matchPath,matchRoutes,parsePath,重定向,renderMatches,resolvePath,不稳定_HistoryRouter,useActionData,useAsyncError,useAsyncValue,useFetcher,useFetch,useFormAction,useHref,useInRouterContext,useLinkClickHandler,useLoaderData,useLocation,useMatch,useMatches,useNavigate,useNavigation,useNavigationType,useOutlet,useOutletContext,useParams,useResolvedPath,useRevalidator,useRouteError,useRouteLoaderData,useRoutes,useSearchParams,useSubmit(

似乎useHistory不是react-router-dom的一部分。

无法在react应用程序中导入useHistory

您可以尝试以下步骤:

  • 安装react路由器dom。npm install—保存react路由器dom
  • Import the history package from react router dom. import { useHistory } from "react-router-dom"
    
  • Assign the history function to a variable (not necessary but. recommended)
    
  • 成功登录后,使用push((函数重定向用户

如果使用react-router-dom@6,则useHistory钩子将被useNavigate钩子替换。

import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
navigate(target);                    // replaces history.push(target)
navigate(target, { replace: true }); // replaces history.replace(target)

如果您特别想要或需要使用useHistory挂钩,则需要安装以前的react-router-dom版本。

npm i -s react-router-dom@5

最新更新