在 reactjs 和 nextjs 构造函数中获取引用错误:未定义 localstorage [英] In reactjs and nextjs constructor getting Reference Error: localstorage is not defined

查看:126
本文介绍了在 reactjs 和 nextjs 构造函数中获取引用错误:未定义 localstorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 reactjs 中制作系统 jsonwebtoken 并使用 nextjs.当我在未定义 localStorage 的浏览器中运行代码时,我发现问题.

i make system jsonwebtoken in reactjs and use nextjs. i find problem when i run the code in browser that is localStorage is not defined.

这是我在文件 AuthStudentContext.js 中的代码

this is my code in file AuthStudentContext.js

import React from 'react'
import axios from 'axios'

const axiosReq = axios.create()
const AuthStudentContext = React.createContext()

export class AuthStudentContextProvider extends React.Component {

    constructor() {
        super()
        this.state = {
            students: [],
            student: localStorage.getItem('student') || {},
            token: localStorage.getItem('token') || "",
            isLoggedIn: (localStorage.getItem('student' == null)) ? false : true
        }
    }

    login = (credentials) => {
        return axiosReq.post("http://localhost:4000/api/login", credentials)
            .then(response => {
                const { token } = response.data
                localStorage.setItem("token", token)

                this.setState({
                    token,
                    isLoggedIn: true
                })

                return console.log(response)
            })
    }

并显示错误 localStorage is not defined

and show error localStorage is not defined

推荐答案

constructor 以及 componentWillMount 生命周期钩子上,服务器仍在渲染组件.另一方面,localStorage 作为浏览器的 Window 全局,因此您只能在呈现组件时使用它.因此,您只能在 componentDidMount 生命周期钩子上访问 localStorage.您可以定义一个空状态,而不是在构造函数上调用 localStorage,并在可以开始调用 localStorage 时更新 componentDidMount 上的状态.

On the constructor as well as componentWillMount lifecycle hooks, the server is still rendering the component. On the other hand, localStorage exists as part of the browser's Window global, thus you can only use it when the component is rendered. Therefore you can only access localStorage on the componentDidMount lifecycle hook. Instead of calling localStorage on the constructor, you can define an empty state, and update the state on componentDidMount when you can start to call localStorage.

constructor() { 
  super()
  this.state = {
    students: [],
    student: undefined
    token: undefined,
    isLoggedIn: undefined
  };
}

componentDidMount() {
  this.login();
  this.setState({
    student: localStorage.getItem('student') || {},
    token: localStorage.getItem('token') || "",
    isLoggedIn: (localStorage.getItem('student' == null)) ? false : true
  });
}

这篇关于在 reactjs 和 nextjs 构造函数中获取引用错误:未定义 localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆