怎样在React-redux应用中使用Firebase实时数据库

时间:2019-10-31
本文章向大家介绍怎样在React-redux应用中使用Firebase实时数据库,主要包括怎样在React-redux应用中使用Firebase实时数据库使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文转载于:猿2048网站▶https://www.mk2048.com/blog/blog.php?id=hh1h0cajib

From 我的简书

Tags: react, react-redux, react-router, firebase.

最近在自学React, 在Safari online books这个平台上看了一套React的视频教程,非常幸运的是这位主讲把代码开源了。有兴趣的可以在这下载源码https://github.com/mannyhenri/working-with-redux, 我自己fork了这个项目,并在此基础之上,做了一些修改和学习。以下是我的提交历史my code

关于这个项目代码的一些说明,由于源码是从0开始使用react搭建一个简单的notepad项目的,所以,目录1-5是不涉及redux架构的。且在使用redux之前,原作者已经使用了firebase 实时数据库来同步数据。ps:firebase需要翻墙使用。

在后面的redux教程中,是在目录5的基础上搭建react-redux架构,但是用redux改写后,原作者没有使用firebase的数据库了。上图中的首次提交是我跟着视频敲的代码,完成redux架构的一个学习过程。然后我就想着,为啥不接着在此基础上,把firebase的实时数据库也应用到redux架构下呢。然后说干就干,反正是小白学习阶段嘛,坑还是要多踩点的,不然怎么进步呢?

接下说说下几个引入firebase做的几个调整。

首先在src目录下,添加config目录,新建firebase.js。

firebase.js firebase.js详细代码如下:

import firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
    apiKey: "AIzaSyC5kq1z62TiKnFJu-4Wm0akR8tLqWpiouo",
    authDomain: "notepad-4dbc2.firebaseapp.com",
    databaseURL: "https://notepad-4dbc2.firebaseio.com",
    projectId: "notepad-4dbc2",
    storageBucket: "notepad-4dbc2.appspot.com",
    messagingSenderId: "909505690107"
};
firebase.initializeApp(firebaseConfig);

const databaseRef = firebase.database().ref();
const notesRef = databaseRef.child("notes");

export default notesRef;

接下来去修改action.js文件

import notesRef from '../config/firebase.js';
import _ from 'lodash';

export const fetchNotes = () => async dispatch => {
    notesRef.on("value", snapshot => {
        const fbStore = snapshot.val();
        const store = _.map(fbStore, (value, id) => {
            return {
                id: id,
                title: value.title,
                details: value.details
            }
        });
        dispatch({
            type: 'GET_NOTES',
            payload: store
        });
    });
};

export const addNewNote = note => async dispatch => {
    notesRef.push(note, response => response);
};

export const removeNote = id => async dispatch => {
    notesRef.child(id).remove();
};

export const updateNote = note => async dispatch=> {
    notesRef.child(note.id).update({ details: note.details });
}

然后再去修改reducers.js ,然后你会发现reducers.js代码少了很多有木有。为啥switch里面只剩下一个‘GET_NOTES’的action呢?再回看上面的action文件就能找到答案了。使用firebase的实时数据库添加,删除,修改记录后都会触发 notesRef.on("value"这个事件,然后在它的callback里读取database的最新数据后,统一dispatch给一个‘GET_NOTES’类型的action,并将最新数据传递给payload。这样到传到reducers后就可以正确更新state了。 reducers.js

const initialState = {
    notes: [],
    name: 'Smallsun'
}

export default (state = initialState, action) => {
    switch (action.type) {
        case 'GET_NOTES': 
            return {
                ...state,
                notes: action.payload
            }  
        default:
            return state
    }
}

最后来看一下程序的界面吧!

2018年5月22日更新:在原来的基础上加上了React Router页面导航功能,详见我的github https://github.com/ylzsmallsun/working-with-redux/commits/master/5.

参考文章: https://medium.com/quick-code/how-to-integrate-react-redux-and-firebase-in-3-simple-steps-c44804a6af38


更多专业前端知识,请上【猿2048】www.mk2048.com

原文地址:https://www.cnblogs.com/htmlandcss/p/11770663.html