Safari reporting “Unexpected token 'const' ” when I open my React App

陌路散爱 提交于 2021-02-19 05:35:20

问题


I have problem with my React App opening in Safari and especially my private routing.Error:

SyntaxError: Unexpected token 'const'

I have ordinary rooting function:

function App() {
  return (
    <Router history={history}>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/login" component={Login} />
        <PrivateRoute path="/dash" component={Dashboard} />
        <PrivateRoute path="/filters" component={Filters} />
        <PrivateRoute path="/profile" component={Profile} />
        <PrivateRoute path="/map" component={Map} />
        <PrivateRoute path="/bookmarks" component={Bookmarks} />
        <PrivateRoute path="/client/:planID/:isLarge" component={Client} />
        <PrivateRoute
          path="/analyses/:planID/:isLarge"
          component={Analyses}
        />
      </Switch>
    </Router>
  );
}

The problem is with this PrivateRoute because when I remove the import and tags it is not displaying the error. Here is my private route file:

import React from "react";
import { Route, Redirect } from "react-router-dom";

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};
export default PrivateRoute;

I suspect something in returning is not right for Safari but I do not know what. Also this is working in this way on Chrome, Mozilla, IE and Edge. Only Safari have problems.

UPDATE:

Here is the screenshot of issue in Safari:


回答1:


Fixed it! The problem was arrow function declaration. Safari 5.1 is really bad and for getting well with all browsers it is better to avoid ES6 syntax arrow functions. From this:

const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );

I transformed code to this:

function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={function(props) {
        return sessionStorage.getItem("Token") ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        );
      }}
    />
  );


来源:https://stackoverflow.com/questions/60295047/safari-reporting-unexpected-token-const-when-i-open-my-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!