React.js-Localstorage未定义错误显示

时间:2018-09-24 07:07:10

标签: reactjs local-storage meta-tags serverside-rendering

我试图通过Meta标签使我的网站SEO友好。 我正在我的应用程序中实现服务器端渲染。此后,我得到以下错误“ ReferenceError:未定义localStorage”。请帮助解决该问题。

正在寻找您的答复。

我的package.json

{


 "main": "server.js",
 "scripts": {
  "start-dev": "NODE_ENV=development webpack -w & NODE_ENV=development node server.js",
  "test": "echo \"Error: no test specified\" && exit 1"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "dependencies": {
  "axios": "^0.18.0",
  "express": "^4.15.3",
  "firebase": "^4.12.1",
  "html2canvas": "^1.0.0-alpha.12",
  "react": "^16.2.0",
  "react-adsense": "0.0.5",
  "react-dom": "^16.2.0",
  "react-facebook-login": "^4.0.1",
  "react-google-login": "^3.2.1",
  "react-meta-tags": "^0.3.0",
  "react-router-dom": "^4.2.2",
  "react-router-match-as-promised": "^1.0.5",
  "react-scripts": "1.1.1",
  "react-share": "^2.1.1",
  "react-slick": "^0.22.3"
 },
 "devDependencies": {
  "autoprefixer": "^7.1.2",
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.1",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-react-app": "^3.1.2",
  "babel-preset-stage-0": "^6.24.1",
  "css-loader": "^0.28.4",
  "extract-text-webpack-plugin": "^2.1.2",
  "file-loader": "^0.11.2",
  "postcss-loader": "^2.0.6",
  "webpack": "^3.1.0",
  "webpack-node-externals": "^1.7.2"
 }
}

所有页面中常用的元标记。 Home.js

<code>
import React, { Component } from 'react';
import axinst from '../common';
import {TabBox,TabBox2,TabBox3} from '../common/tabbox';
import Ads  from '../common/ads';
import SubscribeFrm from '../common/subscribefrm';
import MetaTags from 'react-meta-tags';
import AdSense from 'react-adsense';
import Loader from '../common/loader';

class Home extends Component {
  constructor(props) {
    super(props);
  }

  state = {
    header:[],
    otherSports:[],
    wizztalk:[],
    sports:[],
    isProgress:'',
    activeCat: '',
    metaTitle:'',
    metaDesc:'',
    metaKey:''
  }

  componentDidMount(){


    // axinst.get('/home')
    this.setState({isProgress:true});
    axinst.get('/home').then(response => {
      this.setState({isProgress:false});
      const header = response.data.data.Header;
      const sports = response.data.data.Sports;
      const otherSports = response.data.data.OtherSports;
      const wizztalk = response.data.data.Wizztalk;
      const metaTitle = response.data.data.metaTitle;
      const metaDesc = response.data.data.metaDesc;
      const metaKey = response.data.data.metaKeyword;
      this.setState({header});
      this.setState({sports});
      this.setState({otherSports})
      this.setState({wizztalk});
      this.setState({metaTitle});
      this.setState({metaDesc});
      this.setState({metaKey});
    }).catch(function (error) {
      // console.log(error);
      // console.log('error');
    });
  }

  render() {
    const hD = this.state.header;
    const sport = this.state.sports;
    return (
    <div id="maincontent">
        <MetaTags>
          <title>{this.state.metaTitle}</title>
          <meta name="title" content={this.state.metaTitle} />
          <meta name="keywords" content={this.state.metaKeyword} />
          <meta name="description" content={this.state.metaDesc} />
          <meta name="og:description" content={this.state.metaDesc} />
          <meta name="og:title" content={this.state.metaTitle} />
          <meta name="og:image" content={process.env.PUBLIC_URL +"/images/logo.png"}/>
        </MetaTags>
</code>

3 个答案:

答案 0 :(得分:9)

在服务器上进行渲染时,您没有浏览器,因此无法访问该浏览器提供的所有API,包括localStorage

在同时在服务器和客户端(浏览器)上运行的JavaScript代码中,通常的做法是使用if子句来检查是否检查了window。 “窗口”是浏览器为浏览器提供的所有API提供的根对象。

示例:

if (typeof window !== 'undefined') {
    console.log('we are running on the client')
} else {
    console.log('we are running on the server');
}

在您的情况下,您想在这样的localStorage子句中将对if的呼叫放在电话上,例如:

if (typeof window !== 'undefined') {
    localStorage.setItem('myCat', 'Tom');
}

答案 1 :(得分:0)

您可以将a polyfill添加到您的应用中。即index.js中的某处:

if (!window) {
    require('localstorage-polyfill');
}

答案 2 :(得分:0)

这个班轮为我做到了:

const checkout = typeof window !== 'undefined' ? localStorage.getItem('checkout') : null