You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom 4.1.1版本中'Navigate'未导出错误的解决方案咨询

Fixing 'Navigate' is not exported from 'react-router-dom' in v4.1.1

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

  • Navigate is a component introduced in react-router-dom v6—it doesn't exist in v4.1.1. The equivalent in v4 is Redirect.
  • useLocation is 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 the location object.

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 Navigate with Redirect: This is the v4.x component for handling redirects, and it supports passing state via the to object (just like you did with Navigate).
  • Removed useLocation: We get the location object either through withRouter injection or the Route render callback—both are supported in v4.1.1.
  • Maintained your authentication logic: The core check for isAuthenticated stays exactly the same, so you don't have to modify your auth state setup.

内容的提问来源于stack exchange,提问作者user20659824

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:37:30