昨天我更改了检查身份验证的方式,将逻辑放在React应用程序的index.js文件中。我想测试一些东西,虽然我在beforeAll块中设置了模拟localStorage,但是却收到一条错误消息,说未定义localStorage。
这是最好的方法吗?还是有更好的方法,或者我将如何避免此错误?
这是索引文件:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Router } from "react-router-dom";
import { createStore, applyMiddleware, compose } from "redux";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import history from "./history";
import jwt_decode from 'jwt-decode';
import "./style.css";
import "semantic-ui-css/semantic.css";
import reducer from "./reducers/index";
import { getCurrentUser, logout } from "./actions/authActions/authActions";
export const store = createStore(reducer, compose(applyMiddleware(thunk, logger)));
if (localStorage.getItem('token')) {
// decode token and get user info and expiration
// decoded = ID
const decoded = jwt_decode(localStorage.getItem('token'))
// set User and isAuthenticated (to keep user logged in)
store.dispatch(getCurrentUser(decoded._id))
// check for expired token
const currentTime = Date.now() / 1000
if (decoded.exp < currentTime) {
// Log out the user
store.dispatch(logout())
// Rediret to login page if token is expired
history.push('/login')
}
}
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById("root")
);
答案 0 :(得分:0)
在调用localStorage方法之前,您可以:
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
if(lsTest() === true){
if (localStorage.getItem('token')) {
//...
}
}else{
history.push('/enable-browser-storage-page');
}
这可确保用户启用了本地存储。如果不是,请将该用户重定向到指示如何启用的页面。
此外,您可以添加一个功能来检查本地存储是否可用:
public function getDiscountedPriceAttribute()
{
return ($this->discount * $this->price) / 100;
}