【发布时间】:2021-05-09 18:32:37
【问题描述】:
谁能帮我解决 Next JS 和 localstorage 的问题。我正在构建一个电子商务应用程序,当用户将商品放入购物篮时,我希望能够将其保存到本地存储中。我当前的实现不起作用,我收到一条错误消息,提示“无法读取未定义的属性 'basket'”。下面是我的代码 sn-p。
export const StateProvider = ({ children }) => {
const initialState = () => {
if (typeof window !== 'undefined') {
return {
basket:
window.localStorage.getItem('basket') === null
? []
: window.localStorage.getItem('basket'),
viwedItems: [],
saved: [],
};
}
};
const [state, dispatch] = useReducer(productReducer, initialState());
const [durationNotification, setDurationNotification] = useState(true);
const [showMiniBasket, setMiniBasket] = useState(false);
useEffect(() => {
window.localStorage.setItem('basket', state.basket);
}, [state.basket]);
【问题讨论】:
标签: reactjs next.js local-storage