怎樣在React-redux應(yīng)用中使用Firebase實(shí)時(shí)數(shù)據(jù)庫

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

最近在自學(xué)React, 在Safari online books這個(gè)平臺(tái)上看了一套R(shí)eact的視頻教程,非常幸運(yùn)的是這位主講把代碼開源了。有興趣的可以在這下載源碼https://github.com/mannyhenri/working-with-redux, 我自己fork了這個(gè)項(xiàng)目,并在此基礎(chǔ)之上,做了一些修改和學(xué)習(xí)。以下是我的提交歷史mycode:

mygit

關(guān)于這個(gè)項(xiàng)目代碼的一些說明,由于源碼是從0開始使用react搭建一個(gè)簡(jiǎn)單的notepad項(xiàng)目的,所以,目錄1-5是不涉及redux架構(gòu)的。且在使用redux之前,原作者已經(jīng)使用了firebase 實(shí)時(shí)數(shù)據(jù)庫來同步數(shù)據(jù)。ps:firebase需要翻墻使用。

在后面的redux教程中,是在目錄5的基礎(chǔ)上搭建react-redux架構(gòu),但是用redux改寫后,原作者沒有使用firebase的數(shù)據(jù)庫了。上圖中的首次提交是我跟著視頻敲的代碼,完成redux架構(gòu)的一個(gè)學(xué)習(xí)過程。然后我就想著,為啥不接著在此基礎(chǔ)上,把firebase的實(shí)時(shí)數(shù)據(jù)庫也應(yīng)用到redux架構(gòu)下呢。然后說干就干,反正是小白學(xué)習(xí)階段嘛,坑還是要多踩點(diǎn)的,不然怎么進(jìn)步呢?

接下說說下幾個(gè)引入firebase做的幾個(gè)調(diào)整。

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

firebase.js

firebase.js詳細(xì)代碼如下:

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;
firebase page

接下來去修改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 ,然后你會(huì)發(fā)現(xiàn)reducers.js代碼少了很多有木有。為啥switch里面只剩下一個(gè)‘GET_NOTES’的action呢?再回看上面的action文件就能找到答案了。使用firebase的實(shí)時(shí)數(shù)據(jù)庫添加,刪除,修改記錄后都會(huì)觸發(fā) notesRef.on("value"這個(gè)事件,然后在它的callback里讀取database的最新數(shù)據(jù)后,統(tǒng)一dispatch給一個(gè)‘GET_NOTES’類型的action,并將最新數(shù)據(jù)傳遞給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
    }
}

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


notepad page

2018年5月22日更新:在原來的基礎(chǔ)上加上了React Router頁面導(dǎo)航功能,詳見我的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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容