javascript - 在 reactjs 和 nextjs 构造函数中获取引用错误 : localstorage is not defined

标签 javascript node.js reactjs next.js

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

这是我在文件 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 未定义

最佳答案

正如大家已经提到的,NextJS 在客户端和服务器上都运行。服务器上没有localStorage ,因此 undefined错误。
但是,另一种解决方案是在访问 localStorage 之前检查服务器上是否正在运行 nextjs。 . IE

const ISSERVER = typeof window === "undefined";

if(!ISSERVER) {
 // Access localStorage
 ...localStorage.get...
}

关于javascript - 在 reactjs 和 nextjs 构造函数中获取引用错误 : localstorage is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59540321/

相关文章:

javascript - Kendo UI Grid 在初始读取时未显示微调器/加载图标

html - 打包 NodeWebkit 和 Web 服务器

javascript - 每当可选 Prop 发送到子组件时显示错误

JavaScript、React - 发送多个同时的 ajax 调用

javascript - React.js : submit form programmatically does not trigger onSubmit event

javascript - 以 ECMAScript 5 及更高版本为目标时,八进制文字不可用

javascript - 每次输入后如何重置列表?

node.js - javascript/socket.io -- Socket.IO 授权与 Twitter 问题

javascript - 复制 stackoverflow 标签系统的功能

javascript - Node.js SIGTERM 实现注意事项