javascript - 无法解析来自 React Firebase 对象的数据

标签 javascript reactjs firebase parsing react-redux

我有以下功能组件,它尝试使用 react-redux-firebase 库从我的 Firebase 实时数据库查询数据:

export default function Questions() {
    useFirebaseConnect([{ path: 'questions' }])

    const questionList = useSelector(state => state.firebase.data['questions'])

    for (var test in questionList) {
        // THIS WORKS
        var propValue = questionList['12342134234']['content']
        console.log(propValue)
    }
    // THIS RESULTS IN AN ERROR
    var propValue = questionList['12342134234']['content']
    console.log(propValue)

    }
}

现在的问题是,我无法直接访问 firebase 对象的值。当我迭代返回的对象时,我可以查看属性名称。但是,当我尝试直接访问这些属性(通过 for 循环外部的 questionList[propName])时,我的应用程序崩溃,因为该值未定义。

将值记录到控制台,我得到: enter image description here

我不明白为什么在 for 循环内执行 console.log(questionList['12342134234']) 有效,但当我在外部执行时,我得到 undefined 我的应用程序崩溃了。这对我来说没有意义。

我还可以使用 JSON.stringify() 读取对象,但是当我尝试使用 JSON.parse() 解析它时,我得到 语法错误:JSON 解析错误:意外的标识符“未定义”。这是字符串化文本的输出: enter image description here

我的处理方式正确吗?我如何从这个返回的对象中获取各个属性值?

Update: So when I do the following:

setTimeout(() => {
        // let parsedList = JSON.stringify(questionList, null, 2)
        // let parsed = JSON.parse(parsedList)
        console.log('BP: ', questionList['12342134234'])
    }, 6000)

我得到以下输出: enter image description here 这意味着它可以工作一次,但也会崩溃。

最佳答案

这通常是由非对象数据引起的,你必须先解析数据。

尝试使用JSON.parse,那么您应该能够直接访问值:

let parsedList = JSON.parse(questionList)
console.log(parsedList['12342134234'])

更新

当你得到问题列表时,它似乎已经被解析了。

如果它与settimeout一起使用,那么firebase请求可能会导致问题,检查问题数据是否加载:

import { isLoaded } from 'react-redux-firebase'`

...

const questionList = useSelector(state => state.firebase.data['questions'])

if (isLoaded(questionList)) {
  console.log('BP: ', questionList['12342134234'])
}

关于javascript - 无法解析来自 React Firebase 对象的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59570758/

相关文章:

reactjs - 当我的数据在接下来的 13 年发生更改时,如何重新渲染?

java.lang.IllegalStateException : Default FirebaseApp is not initialized in this process

java - 在 Struts 2 中使用 getText() 获取属性

reactjs - 使用 babel polyfill 后,bundle.js 仍然包含箭头函数和默认参数

javascript - 运行 javascript 函数后无法识别 Css 格式

reactjs - 如何设置webpack的根目录

javascript - promise 只能与 then 函数一起正常工作

java - list 合并失败并出现多个错误,请参阅日志错误

javascript - 与数据库连接和输入处理有关的 ionic 问题

javascript - 使用Phonegap和JQuery mobile时,你会使用JS模板框架吗?