Firebase 到 localStorage

Firebase to localStorage

我想将对象作为 JSON 字符串保存到本地存储以供离线渲染。此时只希望写入函数进行测试。我的问题是为什么只有一个 key/value 字符串(数组)写入 localStorage?

我试过的

这是我要保存的对象。

Addr_states
 -JhMZ6QjAm0FRAcRjivP
 Country: 
 State: 
 -JhMdqTXuayd00hqkp_E
 Country: 
 State: 
 -JhMgVVy_58upfBjf0sO
 Country:  
 State: 
 -JhMjte-ujgsmxgyX8Zf
 Country: 
 State: 
 -JhMkPrScGjvRNVna4Hp
 Country: 
 State: 
 -JhOYj6j4lW4Y38wJDsN
 Country: 
 State: 

到目前为止,这是我的代码:

function myDataStore (myDataPass)
                    {localStorage.setItem("States", JSON.stringify(myDataPass));}

if (myStorageStatus == true)
{

    if (myOnlineStatus == false)
    {
        myDataSource = "Local Storage";
    }
    else
    {
        myDataSource = "Web Firebase";
        localStorage.removeItem("States");
        var myDataRead = new Firebase('https://myappURL/Addr_states');
        myDataRead.on('child_added', function(snapshot) {
            myDataGroup = snapshot.val();
            console.log(myDataGroup);
            myDataStore (myDataGroup);
        });


    }
}

备注

您的代码正在响应 child_added 个事件:

var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('child_added', function(snapshot) {

A child_added event fires for every child that is added under the indicated node。因此,在您的情况下:每个州都会触发 child_added 事件。

这也意味着您的回调函数会为每个状态调用。然后你用那个状态的信息覆盖本地存储中的任何内容:

myDataStore (myDataGroup);

所以基本上您的本地存储现在将包含来自 Firebase 的任何最后状态。

鉴于您将本地存储命名为 States,您似乎想将所有状态存储在其中。这可以通过监听 Firebase 的 value 事件最容易地完成:

var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('value', function(snapshot) {
    myDataGroup = snapshot.val();
    console.log(myDataGroup);
    myDataStore (myDataGroup);
});

如果你还想遍历各个状态,你可以使用forEach:

var myDataRead = new Firebase('https://myappURL/Addr_states');
myDataRead.on('value', function(allStates) {
    allStates.forEach(function(stateSnapshot) {
        console.log(stateSnapshot.val());
    });
});