【发布时间】:2020-10-18 21:39:44
【问题描述】:
我有一个简单的购物网站,其数据来自无头 CMS 系统。我正在使用 nextJS/React 来构建网站。当用户将商品添加到购物车时,我想使用 firebase 来保持状态,因为用户浏览不同的页面。但是,当用户导航到不同的页面时,我会丢失该州的所有数据以及 firebase。主要问题是我无法将初始购物车状态设置为 firebase 数据。我该如何解决这个问题,以便我可以使用 firebase 数据来保持购物车状态?
import React, { useState, useEffect } from 'react';
import Layout from './../components/Layout';
import contextCart from './../components/contextCart';
import firebase from '../data/firestore';
export default function MyApp({ Component, pageProps }) {
//any way to set the initial cart state to data from firebase???
const [ cart, setCart ] = useState([]);
const addToCart = (product) => {
setCart((prevCartState) => {
return [ ...prevCartState, product ];
});
firebase.database().ref().set(cart);
};
//componentDidUpdate => listen for cart changes and update the localStorage
useEffect(
() => {
firebase.database().ref().set(cart);
},
[ cart ]
);
//componentDidMount => run the effect only once and run cleanup code on unmount
useEffect(() => {
//effect code
firebase.database().ref().once('value').then(function(snapshot) {
setCart(snapshot.val() || []);
});
//returned function will be called on component unmount aka cleanup code
//return () => { /*any cleanup code*/ };
}, []);
return (
<contextCart.Provider value={{ cart: cart, addToCart: addToCart }}>
<Layout>
<Component {...pageProps} />
</Layout>
</contextCart.Provider>
);
}
【问题讨论】:
-
我无法像我希望的那样使用 localStorage 或 cookie,因为 nextJS 页面在渲染阶段(服务器渲染与客户端渲染)无法识别文档或 localStorage
标签: reactjs firebase react-hooks use-state