【问题标题】:React Class method returns undef instead of a verified valueReact Class 方法返回 undef 而不是经过验证的值
【发布时间】:2021-03-28 00:35:01
【问题描述】:

这个问题看起来很基本,但我被困在这个问题上。我有一个不是组件的类,我用它来初始化数据库并执行数据库 CRUD 操作。该类有一个方法 readMatrix 从数据库中读取字典并将其作为矩阵返回。我可以在控制台中检查矩阵的值,它是正确的。然而,返回给调用函数的值是“未定义的”,而不是我在控制台日志中看到的。我尝试使用 Redux/Hooks 来修复它,发现这种方式对于像我这样的新手来说太复杂了(我使用函数/钩子作为组件,但是一个用于 DB 管理的类)。

这是类的代码:

readMatrix (r,c,id) {
    const row = new Array(c).fill(null);
    var tempMatrix=[];
        for (let i=0; i<r; i++){
        tempMatrix.push([...row])
    }

    var restaurantRef = app.database().ref("/restaurants");
    restaurantRef.orderByKey().equalTo("1").on("child_added", function(snapshot){           
        //  console.log(snapshot.child("/layout").val());
        var restaurant=snapshot.child("/layout").val();
        for (const [key, value] of Object.entries(restaurant)) {
              let i=key;
              for (const [rowkey, rowvalue] of Object.entries(value)){
                  let j=rowkey;
                  tempMatrix[i][j]=rowvalue;                      
              }
        }
            console.log(tempMatrix);
    return(tempMatrix); 
        
}); 

}

这是调用函数:

    useEffect(()=>{
            
    setMatrix(FirebaseClass.readMatrix(matrixHeight,matrixWidth, 1))
    console.log(matrix);    
    
  }, []);

你知道那里出了什么问题吗?

【问题讨论】:

标签: javascript reactjs firebase react-hooks


【解决方案1】:

感谢您的回答

这是修复它的唯一想法。

  1. 将 readMatrix 声明为异步。
  2. 通过以下方式获取矩阵中的值:
FirebaseClass.readMatrix(matrixHeight,matrixWidth, 1).then(setMatrix)

希望答案比问题更清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多