我目前正在使用 next.js 开发我的第一个会员区。现在我想在 localStorage 中存储一些数据(token、expiresAr、userInfo) - 顺便说一句,稍后这些数据将存储在仅 http 的 cookie 中。
使用以下代码我收到错误:“LocalStorage 未定义”:
const AuthProvider = ({ children }) => {
const token = localStorage.getItem("token");
const userInfo = localStorage.getItem("userInfo");
const expiresAt = localStorage.getItem("expiresAt");
const [authState, setAuthState] = useState({
token,
expiresAt,
userInfo: userInfo ? JSON.parse(userInfo) : {},
});
const setAuthInfo = ({ token, userInfo, expiresAt }) => {
localStorage.setItem("token", token);
localStorage.setItem("userInfo", JSON.stringify(userInfo));
localStorage.setItem("expiresAt", expiresAt);
setAuthState({
token,
userInfo,
expiresAt,
});
};Run Code Online (Sandbox Code Playgroud)
我已经尝试使用以下片段:
if (typeof window !== 'undefined') {
const token = localStorage.getItem("token"); …Run Code Online (Sandbox Code Playgroud) 我正在使用动态图像。在 localhost 上一切正常,但是当我在 vercel 上部署 next.js-app 时,只显示后备图像(默认图像出现 404 错误)。
顺便说一句,当我对图像进行硬编码时,而不是使用动态路径,一切正常。所以我认为问题出在动态路径中的某个地方(?)。
这是相关代码:
function isImageValid(src) {
let promise = new Promise((resolve) => {
let img = document.createElement("img");
img.onerror = () => resolve(false);
img.onload = () => resolve(true);
img.src = src;
});
return promise;
}
function Img({ src, fallbackSrc, ...rest }) {
const imgEl = React.useRef(null);
React.useEffect(() => {
isImageValid(src).then((isValid) => {
if (!isValid) {
imgEl.current.src = fallbackSrc;
}
});
}, [src]);
return <img {...rest} ref={imgEl} src={src} />;
}
const ItemImage = ({ …Run Code Online (Sandbox Code Playgroud)