admin管理员组

文章数量:1332359

I am using localStorage a lot on my authenticated ponents in my react application to get user details from local storage as well as storing them on login.

When I build my app, it throws ReferenceError: localStorage is not defined.

I know this could be because node does not have access to localStorage and thus the error.

How can I solve the problem?

Here is an example of code I use in my ponent.

import React, {PropTypes} from 'react';
import AccountBasicInfo from '../ponents/AccountBasicInfo';


export class Account extends React.Component {


    userBasicInfo(){
      const user = localStorage.getItem('User') ? JSON.parse(localStorage.getItem('User')) :{};
      const cashback = localStorage.getItem('cashback') ? JSON.parse(localStorage.getItem('cashback')) :{};
    }
    render(){
      return(
          <div>
              <AccountBasicInfo theme="theme2" item={this.userBasicInfo.bind(this)()}/>
          </div>
      );
    }
}



export default Account;

I am using localStorage a lot on my authenticated ponents in my react application to get user details from local storage as well as storing them on login.

When I build my app, it throws ReferenceError: localStorage is not defined.

I know this could be because node does not have access to localStorage and thus the error.

How can I solve the problem?

Here is an example of code I use in my ponent.

import React, {PropTypes} from 'react';
import AccountBasicInfo from '../ponents/AccountBasicInfo';


export class Account extends React.Component {


    userBasicInfo(){
      const user = localStorage.getItem('User') ? JSON.parse(localStorage.getItem('User')) :{};
      const cashback = localStorage.getItem('cashback') ? JSON.parse(localStorage.getItem('cashback')) :{};
    }
    render(){
      return(
          <div>
              <AccountBasicInfo theme="theme2" item={this.userBasicInfo.bind(this)()}/>
          </div>
      );
    }
}



export default Account;
Share Improve this question asked Aug 10, 2016 at 15:53 Harsh MaurHarsh Maur 891 gold badge1 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

If you need to run the same, unmodified code on node, which does not have a native localStorage implementation, you could consider using a shim such as node-localstorage.

You could also consider rewriting your code to use an alternative means of storing information.

本文标签: javascriptReferenceError localStorage is not defined in ReactJS BuildStack Overflow