尝试导入错误:未从“ react-router-dom”导出“ PrivateRoute”

时间:2020-01-09 07:24:20

标签: javascript reactjs react-router-dom

我尝试使用PrivateRoute like this example创建一个react-router-dom,但出现这样的错误:

Attempted import error: 'PrivateRoute' is not exported from 'react-router-dom'.


反应: 16.12.0
react-router-dom: 5.1.2



index.js 中,我导入BrowserRoute并在ReactDOM.render()中使用它们,如下所示:

ReactDOM.render(
  <BrowserRouter><App /></BrowserRouter>,
  document.getElementById('root')
);

App.js 中,我渲染了<Home />组件,如下所示:

function App() {
  return (
    <div className="App">
      <Home />
    </div>
  );
}

然后我像这样从PrivateRouter组件中的react-router-dom导入<Home />

import { 
  Switch,
  // Route,
  PrivateRoute 
} from 'react-router-dom';

而我在PrivateRoute函数内部使用render()是这样的:

<Switch>
  <PrivateRoute path="/customer">
    <RootContent 
      displayContent="CUSTOMER" 
      responseCode={this.state.responseCode}
      responseStatus={this.state.responseStatus}
      responseMessage={this.state.responseMessage}
      responseData={this.state.responseData}
      getApiSuccess={this.state.getApiSuccess}
      USER_TOKEN={this.state.USER_TOKEN}
    />
  </PrivateRoute>
</Switch>



我还是ReactJS的新手。
希望您能帮助我,谢谢。

2 个答案:

答案 0 :(得分:1)

您不能从react-router-dom导入PrivateRoute。检查示例

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
  useHistory,
  useLocation
} from "react-router-dom";

在示例中-PrivateRoute是一个需要先导出然后再导入的函数-它不是从react-router-dom导入的

function PrivateRoute({ children, ...rest }) {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        fakeAuth.isAuthenticated ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
  );
}

答案 1 :(得分:0)

您需要创建专用路由,因为在react-router-dom

中该路由不可用

在官方文档中看到的privateRoute都是为私有路线创建的自定义组件。

以示例为例

function PrivateRoute({ children, ...rest }) {
  return (
    <Route
      {...rest}
      render={({ location }) =>
        fakeAuth.isAuthenticated ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
  );
}