我已经设置了一个 Provider 来为使用useContext
. 因此,我试图利用本地存储为用户图像(头像等)保存一些状态
首先,我试图为用户保留头像,本质上是从 express 中保存他们的 ID,然后在我调用 Cloudinary(图像托管服务)时使用它。
我想我已经接近了(因为我获得了头像工作的默认图像占位符),但我无法设置本地存储。
import React, { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';
var initialState = {
userId: null,
avatar: '/static/uploads/profile-avatars/placeholder.jpg'
};
var UserContext = React.createContext();
function getLocalStorage() {
return Object.keys(initialState).forEach(item => {
dynamic(
() =>
Object.keys(initialState).forEach(
val => (initialState[window.localStorage.getItem(item)] = val)
),
{
ssr: false
}
);
});
}
function setLocalStorage() {
Object.keys(initialState).forEach(item => {
console.log('item setLocalStorage', item);
dynamic(
() =>
window.localStorage.setItem(
item,
Object.values(initialState).forEach(item => item)
),
{
ssr: false
}
);
});
}
function UserProvider({ children }) {
var [userImages, setUserImages] = useState(() => getLocalStorage() || initialState);
var [userId, setUserId] = useState(userImages.userId);
useEffect(() => {
setLocalStorage();
}, [userId]);
return (
<UserContext.Provider
value={{
userImages,
setUserImages,
userId,
setUserId
}}
>
{children}
</UserContext.Provider>
);
}
export default UserContext;
export { UserProvider };
提前谢谢您,父亲节快乐!