我正在尝试将会话数据存储到localStorage,但是我收到错误。 “ReferenceError:localStorage未定义”
这是代码。
import alt from '../alt';
import UserActions from '../actions/UserActions.js';
// To Do: Inplement LocalStorage Polyfill
class UserStore {
constructor() {
this.initialize();
this.bindListeners({
onLoginSucceeded: UserActions.LOGIN_SUCCEEDED
});
}
initialize() {
this.setState({
// There's an error here.
_loggedIn: localStorage.getItem('loggedIn'),
_authToken: localStorage.getItem('authToken'),
_userId: localStorage.getItem('userId'),
_profile: localStorage.getItem('profile')
});
}
onLoginSucceeded(data) {
this.setState({
_loggedIn: true,
_authToken: data.authToken,
_userId: data.userId,
_profile: data.profile,
_user: data.user
});
// There's no error here.
localStorage.setItem('authToken', data.authToken);
localStorage.setItem('loggedIn', data.loggedIn);
localStorage.setItem('userId', data.userId);
localStorage.setItem('profile', data.profile);
}
getCurrentUser() {
return this.state._user;
}
isLoggedIn() {
}
}
export default alt.createStore(UserStore, 'UserStore');
我是es6的新手,所以我可能会错过一些东西,但我找不到类似于我无法在课堂内调用全局对象的东西。 如果您对此错误有任何了解,将会很有帮助。
[编辑] 这适用于es6fiddle http://www.es6fiddle.net/ichmbt0e/
class UserStore {
constructor() {
this.initialize();
}
initialize() {
this.setState({
_loggedIn: localStorage.getItem('loggedIn'),
_authToken: localStorage.getItem('authToken'),
_userId: localStorage.getItem('userId'),
_profile: localStorage.getItem('profile')
});
}
isLoggedIn() {
}
}
答案 0 :(得分:1)
我发现从localStorage检索数据时我需要使用Alt.bootstrap。
// client.js
import 'es6-shim';
import 'whatwg-fetch';
import Iso from 'iso';
import Router from 'react-router';
import React from 'react';
import routes from './client/routes';
import alt from './client/alt';
Iso.bootstrap(function(state, _, container) {
var userStoreData = {
UserStore: {
_loggedIn: localStorage.getItem('loggedIn'),
_authToken: localStorage.getItem('authToken'),
_userId: localStorage.getItem('userId'),
_profile: localStorage.getItem('profile')
}
}
var new_state = Object.assign(JSON.parse(state), userStoreData)
alt.bootstrap(JSON.stringify(new_state));
Router.run(routes, Router.HistoryLocation, function(Handler) {
var node = React.createElement(Handler);
React.render(node, container);
});
});