Flux(Alt): ReferenceError: localStorage is not defined

Flux(Alt): ReferenceError: localStorage is not defined

我正在尝试将会话数据存储到 localStorage,但收到错误消息。 "ReferenceError: localStorage is not defined"

这是代码。

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 的新手,所以我可能会遗漏一些东西,但我找不到任何东西,比如我不能在 class 中调用全局对象。 如果您对此错误有任何想法,这将很有帮助。

[编辑] 这适用于 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() {

  }

}

我发现从 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);
  });
});