我已在实用程序文件夹的create-react-app中初始化了Firebase,如下所示:
import * as firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
})
export default app
要从我的Firebase实例获取,然后在必要时导入firebase并按以下方式获取:
import React, { useState, useEffect } from 'react'
import logo from './logo.svg'
import firebase from './utils/firebase'
import './App.css'
function App() {
const [values, setValues] = useState(null)
useEffect(() => {
getData()
}, [])
const randomElements = async (array, n) => {
const res = await array
.sort(() => Math.random() - Math.random())
.slice(0, n)
setValues(res)
}
const getData = async () => {
const eachValue = []
await firebase
.firestore()
.collection('customers')
.get()
.then(data => {
data.forEach(doc => eachValue.push(doc.data()))
})
.catch(err => {
console.log(err)
})
return randomElements(eachValue, 12)
}
console.log(values)
return (
<div className='App'>
<header className='App-header'>
<img src={logo} className='App-logo' alt='logo' />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className='App-link'
href='https://reactjs.org'
target='_blank'
rel='noopener noreferrer'
>
Learn React
</a>
</header>
</div>
)
}
export default App
如果我正在运行Firestore模拟器,是否有办法告诉我的React应用程序是从模拟器中获取,而不是从生产数据库中获取?
答案 0 :(得分:1)
是的,您可以将模拟器设置为应用程序要使用的模拟器。如官方文档Connect your app to the emulators中所述,您需要使用以下代码块来指向仿真器。
//Initialize your Web app as described in the Get started for Web documentation
// Firebase previously initialized using firebase.initializeApp().
var db = firebase.firestore();
if (window.location.hostname === "localhost") {
db.settings({
host: "localhost:8080",
ssl: false
});
}
除此之外,您还可以在本文上获得有关如何在Firestore上使用模拟器开发应用程序的完整教程-这样您就可以获取更多信息和有关如何精确执行的详细信息-