代码之家  ›  专栏  ›  技术社区  ›  Ben Cavenagh

Firebase数据的设置状态会导致空白数据

  •  0
  • Ben Cavenagh  · 技术社区  · 6 年前

    我试图在我的React应用程序加载后从Firebase加载所有“组”,但我的行为越来越怪异。它首先会正确地加载它们,因此如果我在数据库中保存了3个组,它将显示1、2、3、4,如下所示: enter image description here

    enter image description here

    componentDidMount(){        
        this.setGroups();
    }
    setGroups(){
        const groupRef = fire.database().ref('groups');
        const groupArray = [];
        const idArray = [];
        groupRef.on('value', snapshot => {
            snapshot.forEach(group => {
                console.log('groupid: ' + group.key);
                idArray.push(group.key);
                let addGroup = {
                    id: group.key,
                    name: group.val().name
                }
                if(groupArray.length !== idArray.length){
                    groupArray.push(addGroup);
                    console.log('pushed');
                }
            })
    
            this.setState(previousState => ({
                groups: groupArray
            }));
        })
    }
    

    然后,这就是我如何处理添加的组:

    handleGroupAdd = (group) => {
        const groupRef = fire.database().ref('groups').child(group.id).set({
            name: group.name,
            id: group.id
        });
        this.setState(previousState => ({
            groups: [...previousState.groups, group]
        }));
    
        this.handleClose();
    };
    

    firebase正确地保存了数据,没有重复的对象,所以它只是将组渲染得一团糟。我猜这是因为州政府在add上搞砸了?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Dyo    6 年前

    对你的问题的解释:

    您正在使用启动快照侦听器 groupRef.on groupRef groupArray 每一次。 因为 在快照函数之外声明,其内容在更新之间保留。

    下面是正在发生的事情:

    1. 第一次渲染:

    setGroup = [1,2,3,4];

    侦听器已触发=>将[1,2,3,4,5]推至 组数组 => 组数组 handleGroupAdd => groups state=[…prevState,5];

    • 仅调用快照侦听器一次:

    groupRef.once('value', snapshot => {...

    • 或者只依靠听众:

    groupRef.on('value', snapshot => {
      let groupArray = [];
      ...
    

    并删除中的状态更新 ;

    you can read the official doc for more info about working with lists of realtime database