【问题标题】:React component state persist from firebaseReact 组件状态从 firebase 持续存在
【发布时间】: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


【解决方案1】:

数据没有更新,因为您没有监听代码中的更改。 您指定在 useEffect 挂钩中获取一次数据,该挂钩仅在初始加载时运行。

要监听更改,您可以这样实现:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
   starCountRef.on('value', function(snapshot) {
   updateStarCount(postElement, snapshot.val());
});

在此处的官方 firebase 文档中了解更多信息:https://firebase.google.com/docs/database/web/read-and-write

我建议你使用像 Redux 这样的状态管理库,甚至是 React 本身的 Context API。 这样做的原因是,firebase 会向您收取数据库的流量费用(这对于 firestore 数据库来说是一个比实时数据库更大的问题,但仍然需要考虑成本)。 使用状态库,您可以检查是否需要从 firebase 获取数据,或者您是否已经拥有您所在州所需的数据。 此外,如果您可以使用 Provider Pattern 拆分代码,则可以在应用程序增长时更轻松地维护逻辑。

【讨论】:

    猜你喜欢
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多