react-router-dom 4.1.1版本中'Navigate'未导出错误的解决方案咨询
Got it, let's break down the issues in your code and fix them without upgrading react-router-dom:
1. Why you're seeing this error
Navigateis a component introduced in react-router-dom v6—it doesn't exist in v4.1.1. The equivalent in v4 isRedirect.useLocationis a hook added in react-router-dom v5.1.0—it's not available in v4.1.1 either. We'll need another way to get thelocationobject.
2. Fixed code options
Here are two valid approaches for v4.1.1:
Option 1: Use withRouter to inject location props
This wraps your component to access routing props like location:
import { Redirect, withRouter, Location } from "react-router-dom"; import { useAppSelector } from "../app/hooks"; // Define a base component that receives location as a prop function PrivateRouteComponent({ children, location }: { children: JSX.Element, location: Location }) { const { isAuthenticated } = useAppSelector((state) => state.auth); return isAuthenticated ? ( children ) : ( // Use Redirect instead of Navigate, pass state via the to object <Redirect to={{ pathname: "/login", state: { from: location } }} /> ); } // Wrap the component with withRouter to inject routing props export const PrivateRoute = withRouter(PrivateRouteComponent);
Option 2: Build PrivateRoute as a custom Route component
This leverages the existing Route component's render callback to get location:
import { Redirect, Route, RouteProps } from "react-router-dom"; import { useAppSelector } from "../app/hooks"; export function PrivateRoute({ children, ...rest }: RouteProps) { const { isAuthenticated } = useAppSelector((state) => state.auth); return ( <Route {...rest} render={({ location }) => isAuthenticated ? ( children ) : ( <Redirect to={{ pathname: "/login", state: { from: location } }} /> ) } /> ); }
Key changes explained
- Replaced
NavigatewithRedirect: This is the v4.x component for handling redirects, and it supports passingstatevia thetoobject (just like you did withNavigate). - Removed
useLocation: We get thelocationobject either throughwithRouterinjection or theRouterender callback—both are supported in v4.1.1. - Maintained your authentication logic: The core check for
isAuthenticatedstays exactly the same, so you don't have to modify your auth state setup.
内容的提问来源于stack exchange,提问作者user20659824
相关产品推荐
相关产品推荐

