背景
我正在尝试构建一个显示许多商店的应用程序,在主屏幕上它是一个功能组件(请注意这一点,因为我需要使用钩子),我有一个滚动视图来显示不同的商店。
我需要的
当用户按下其中一个商店时,应将其重定向到包含该特定商店信息的屏幕。我已经建立了“商店详细信息”屏幕,但是使用静态信息,我想用存储在firestore集合中的数据替换所有这些信息。
题
如何在react native中从Firestore集合中检索数据,然后将每个文档中的数据分配给单独的Touchable Opacity(我知道通过react导航传递参数,我只是不知道在使用时传递哪个参数) Firestore),然后在商店详细信息屏幕中显示该数据?
上下文示例代码
App.js
<NavigationContainer>
<Stack.Navigator initialRouteName={user ? 'Home' : 'Login'}
screenOptions={{cardStyle: { backgroundColor: '#FFFFFF' }}}>
<Stack.Screen name="Home"options={{headerShown: false}}>
{props => <HomeScreen {...props} extraData={user} />}
</Stack.Screen>
<Stack.Screen name="Login" component={LoginScreen} options={{headerShown: false}}/>
<Stack.Screen name="Registration" component={RegistrationScreen} options={{headerShown: false}}/>
<Stack.Screen name="storeDetail" options={{title: ''}}>
{props => <storeDetail {...props} extraData={} />}
</Stack.Screen>
</Stack.Navigator>
</NavigationContainer>
在此文件中,您将看到我已经调用了一些数据(“登录”和“注册”将userData传递到主屏幕),但是,要实现该方法,我取决于我使用的身份验证方法的响应。我想虽然我可能需要传递一些额外数据,但我知道该怎么做,我只是不知道如何填补空白。
在此先多谢!
首先,在您的应用中安装Firebase SDK,以便您可以查询后端。
我不知道您的示例App.js是否代表您应用程序的当前进度状态,但我将假定:
因此,在storeSetails屏幕中,您可以在收到时查询Firestore storeId
,并在成功时将结果保存到状态变量中:
const StoreDetailsScreen = ({ route }) => { // route is passed as a prop by React Navigation
const { storeId } = route.params
const [store, setStore] = useState()
const [loading, setLoading] = useState(true) // show a loading spinner instead of store data until it's available
useEffect(() => {
const fetchQuery = async () => {
const storeData = await firestore()
.collection('stores')
.doc(storeId)
.get() // this queries the database
if (storeData) {
setStore(storeData) // save the data to store state
setLoading(false) // set loading to false
} else {
// something went wrong, show an error message or something
}
}
fetchQuery()
}, [storeId])
if (loading) {
return (
<ActivityIndicator/>
)
}
return (
// ... store details
)
}
然后,您可以使用数据在store
屏幕上渲染内容
<Text>{store.name}</Text>
<Text>{store.email}</Text>
// ...
有关如何在RN中使用Firestore的更多信息:https : //rnfirebase.io/firestore/usage
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句