我正在构建一个简单的路由器来构建我的身份验证机制。该机制将使用存储在localStorage中的JWT来了解我的身份验证。这是我的代码:
import React, { Component } from "react";
import PropTypes from "prop-types";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
}
const isAuthenticated = () => {
let token = localStorage.getItem("jwtToken");
console.log('Local Storage JWT TOKEN:');
console.log(token); // <<<<=== undefined
if (token) {
return true;
}
return false;
};
const AuthenticatedRoute = ({ component: Component, ...rest }) =>
<Route
{...rest}
render={props =>
isAuthenticated()
? <Component {...props} />
: <Redirect
to={{
pathname: "/landing",
state: { from: props.location }
}}
/>}
/>;
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/landing" component={Landing} />
<Route exact path="/logout" component={Logout} />
<Route exact path="/pagenotfound" component={PageNotFound} />
<AuthenticatedRoute exact path="/" component={AppNav} />
<AuthenticatedRoute
exact
path="/:option"
component={AppNav}
/>
<Route component={PageNotFound} />
</Switch>
</Router>
);
}
}
export default App;
由于某些原因,如果没有找到令牌,则localStorage.getItem返回undefined
。我期待null
符合预期here
为什么我的getItem
返回undefined
以及如何解决?