我在 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/