我正在尝试从 firebase 下载用户配置文件并在组件中使用它们。我在使用异步 firebase 函数和 useState 时遇到了问题。在下面的代码中,“profiles”反复被连接,但它似乎没有更新 Swiper 组件中的“cards” Prop ,它仍然得到一个空数组。
import * as React from 'react';
import Swiper from 'react-native-deck-swiper'
import { Card } from '../components/Card'
import { View } from '../components/Themed';
import firebaseSDK from '../database/firebase'
export default function HomeScreen() {
const [profiles,setProfiles] = React.useState([])
firebaseSDK.db
.ref('userProfile')
.once('value')
.then((snapshot)=>{
//this line prints the profiles correctly
console.log("snapshot Val profiles : " + JSON.stringify(Object.values(snapshot.val())))
setProfiles(prevState => prevState.concat(Object.values(snapshot.val())))
})
return (
<View style={styles.container}>
<Swiper
cards={profiles}
renderCard={Card}
/>
}
使用此代码我得到TypeError: undefined is not an object (evaluating 'cards.length')
即使控制台日志显示“配置文件”随着它反复连接而不断变大。正确访问数据的过程是什么?编辑:
关于代码的更多细节
我正在下载的数据如下所示:
{
"id1":{
avatar: "https://placebear.com/200/300",
displayName: 'Fakeman Fakeaccount',
AboutMe: '16 miles away',
uid:1234
},
"id2":{
avatar: "https://placebear.com/200/300",
displayName: 'Joanna, 19',
AboutMe: '2 miles away',
uid:1234
},
"id3":{
avatar: "https://placebear.com/200/300",
displayName: 'Charlie, 32',
AboutMe: '24 miles away',
uid:1234
},
}
cards
接受一个对象数组,这就是为什么我用“[]”初始化 useState 并运行 Object.values
在 snapshot.val()
把它变成一个数组。卡片组件:
export const Card = ({ avatar, displayName, AboutMe, uid }) => (
<Tile
// imageSrc={avatar}
imageSrc={{uri:avatar}}
imageContainerStyle={styles.imageContainer}
activeOpacity={0.9}
title={displayName}
titleStyle={styles.title}
caption={AboutMe}
captionStyle={styles.caption}
containerStyle={styles.container}
key={uid}
featured
/>
)
Swiper
获取一组数据( cards
prop)并使用它来填充多个 Card
组件( renderCard
Prop )编辑2:
感谢@DougStevenson 解决了下载问题(更新状态在
useEffect
块内) const [profiles,setProfiles] = React.useState([
{
avatar: "https://placebear.com/200/300",
displayName: 'Placeholder',
AboutMe: 'Im not real',
uid:"000000000000000000"
},
])
React.useEffect(() => {
firebaseSDK.db
.ref('userProfile')
.once('value', (snapshot)=>{
//returns an array [{...},{...},{...},...]
console.log(JSON.stringify(Object.values(snapshot.val())))
setProfiles(Object.values(snapshot.val()))
})
然而现在setProfiles
将数据 chop 为单个元素数组。我认为这是因为我如何定义初始状态,并且因为我使用的是 TypeScript 模板,所以它对定义很挑剔?编辑 3:
好吧,原来是
Swiper
搞砸了的组件。 Swiper
是一堆View
s,它用长度为 1 的数组初始化,这意味着它创建了 1 View
在堆栈中。当我更新 cards
Prop 它只更新了 1 View
在堆栈中并没有添加更多 View
s。
最佳答案
由于数据库查询是异步的并且不会立即竞争,因此您需要将查询放在 useEffect Hook 中,以便组件知道何时使用新内容进行渲染。
关于javascript - 无法从 Firebase 下载数据 - TypeError : undefined is not an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65119741/