我有以下功能组件,它尝试使用 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]
)时,我的应用程序崩溃,因为该值未定义。
我不明白为什么在 for 循环内执行 console.log(questionList['12342134234'])
有效,但当我在外部执行时,我得到 undefined
我的应用程序崩溃了。这对我来说没有意义。
我还可以使用 JSON.stringify()
读取对象,但是当我尝试使用 JSON.parse()
解析它时,我得到 语法错误:JSON 解析错误:意外的标识符“未定义”
。这是字符串化文本的输出:
我的处理方式正确吗?我如何从这个返回的对象中获取各个属性值?
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)
最佳答案
这通常是由非对象数据引起的,你必须先解析数据。
尝试使用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/