'firebase' is not defined 错误使用 React
'firebase' is not defined error using React
我查看了有此问题的网站,但其中 none 符合我的情况。我不知道为什么 'firebase' 没有定义。我不知道我的代码有什么问题,我需要有人看一下。这个错误发生在我的代码的第 42 行,我不知道为什么会出现这个错误。我尝试在第 42 行使用以下代码访问 firebase 数据库。React.js 代码:
import React, { useState } from 'react';
import { Button } from '@mui/material';
import { storage, db, serverTimeStamp } from "./firebase";
function ImageUpload({username}) {
const [image, setImage] = useState(null); // it will be "choose file" option
const [progress, setProgress] = useState(0);
const [caption, setCaption] = useState(''); // caption will be empty by default, so that it will show placeholder
const handleChange = (e) => { //e.target.files[0] means select the first file that you selected
if (e.target.files[0]) {
setImage(e.target.files[0]); // set the image in state to that
}
};
const handleUpload = () => {
const uploadTask = storage.ref(`images/$(image.name)`).put(image); //storage.ref means get a reference, so access the storage in firebase get a reference to "images" folder were storing everything inside of it. And "image.name" is the file we selected. "put.image" is greabbing the image and putting in there.
uploadTask.on(
"state_changed",
(snapshot) => {
//progress function ...
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
); // It's going to work out a number between 0 and 100 and it's going to give you a sort of exact progress indicator from 0 to 100
setProgress(progress);
},
(error) => {
//error function ...
console.log(error);
},
//what happens after the upload completes function
() => {
//complete function ...
storage
.ref("images") //Go to images folder
.child(image.name) // Go to the image file, and
.getDownloadUrl() // give me the download Url, once it's uploaded it gives us a "download url"
.then(url => {
//post image in db
db.collection("posts").add({
timestamp: serverTimeStamp(), // our "timestamp" is based on the server where our code is living. It's going to help us sort the posts by the correct timings. We want all the recent ones at the top. It adjusts the time with where they are living, so they are consistent with one another. So if you are in la and someone is in london the post will show up at the same time no matter where they are.
caption: caption, // stored the caption in some state, so we can do this
imageUrl: url, // the imageUrl is literally going to be the "download Url" that we just got. We got the uploaded image, and use that as the image url. it's uploaded to firebase storage, and put it in the database. we are using this downloaded link as a part of our post.
username: username, // we have it inside of App.js at the moment
});
setProgress(0); // set progress back to 0 after we reach 100 percent.
setCaption(""); // we want to reset the user forms
setImage(null); // we want to reset the user forms
}) // now we want to post the image to the database
}
) // "on state changed" give me a snapshot, it's an asynchronous process, it isn't immediate. We want to keep track of it, we want to know how long it is going to take. Give me snapshots of the progress.
}
return (
<div>
{/* I want to have... */}
{/* Caption Input */}
{/* File Picker */}
{/* Post Button */}
<progress value={progress} max="100" />
<input type="text" placeholder="Enter a caption..." onChange={event => setCaption(event.target.value)} /> {/* Every key press you do on the input field it's going to fire off an event, updating caption variable on the fly */}
<input type="file" onChange={handleChange} />
<Button onClick={handleUpload}>
Upload
</Button>
</div>
)
}
export default ImageUpload
Firebase.js代码:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/storage';
import "firebase/compat/storage";
const firebaseApp = firebase.initializeApp //
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage().ref();
const serverTimeStamp = firebase.firestore.FieldValue.serverTimestamp;
export { db, auth, storage, serverTimeStamp };
export default db;
您尚未在此文件中导入 Firebase SDK。相反,您可以直接从 firebase.js
本身导出服务器时间戳,如下所示:
const db = firebase.firestore();
// ..
const serverTimestamp = firebase.firestore.Fieldvalue.serverTimestamp;
export { db, serverTimestamp }
然后在需要的地方导入它:
import { serverTimestamp, db } from "./firebase";
db.collection("posts").add({
timestamp: serverTimestamp(),
caption: caption,
imageUrl: url,
username: username,
});
我查看了有此问题的网站,但其中 none 符合我的情况。我不知道为什么 'firebase' 没有定义。我不知道我的代码有什么问题,我需要有人看一下。这个错误发生在我的代码的第 42 行,我不知道为什么会出现这个错误。我尝试在第 42 行使用以下代码访问 firebase 数据库。React.js 代码:
import React, { useState } from 'react';
import { Button } from '@mui/material';
import { storage, db, serverTimeStamp } from "./firebase";
function ImageUpload({username}) {
const [image, setImage] = useState(null); // it will be "choose file" option
const [progress, setProgress] = useState(0);
const [caption, setCaption] = useState(''); // caption will be empty by default, so that it will show placeholder
const handleChange = (e) => { //e.target.files[0] means select the first file that you selected
if (e.target.files[0]) {
setImage(e.target.files[0]); // set the image in state to that
}
};
const handleUpload = () => {
const uploadTask = storage.ref(`images/$(image.name)`).put(image); //storage.ref means get a reference, so access the storage in firebase get a reference to "images" folder were storing everything inside of it. And "image.name" is the file we selected. "put.image" is greabbing the image and putting in there.
uploadTask.on(
"state_changed",
(snapshot) => {
//progress function ...
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
); // It's going to work out a number between 0 and 100 and it's going to give you a sort of exact progress indicator from 0 to 100
setProgress(progress);
},
(error) => {
//error function ...
console.log(error);
},
//what happens after the upload completes function
() => {
//complete function ...
storage
.ref("images") //Go to images folder
.child(image.name) // Go to the image file, and
.getDownloadUrl() // give me the download Url, once it's uploaded it gives us a "download url"
.then(url => {
//post image in db
db.collection("posts").add({
timestamp: serverTimeStamp(), // our "timestamp" is based on the server where our code is living. It's going to help us sort the posts by the correct timings. We want all the recent ones at the top. It adjusts the time with where they are living, so they are consistent with one another. So if you are in la and someone is in london the post will show up at the same time no matter where they are.
caption: caption, // stored the caption in some state, so we can do this
imageUrl: url, // the imageUrl is literally going to be the "download Url" that we just got. We got the uploaded image, and use that as the image url. it's uploaded to firebase storage, and put it in the database. we are using this downloaded link as a part of our post.
username: username, // we have it inside of App.js at the moment
});
setProgress(0); // set progress back to 0 after we reach 100 percent.
setCaption(""); // we want to reset the user forms
setImage(null); // we want to reset the user forms
}) // now we want to post the image to the database
}
) // "on state changed" give me a snapshot, it's an asynchronous process, it isn't immediate. We want to keep track of it, we want to know how long it is going to take. Give me snapshots of the progress.
}
return (
<div>
{/* I want to have... */}
{/* Caption Input */}
{/* File Picker */}
{/* Post Button */}
<progress value={progress} max="100" />
<input type="text" placeholder="Enter a caption..." onChange={event => setCaption(event.target.value)} /> {/* Every key press you do on the input field it's going to fire off an event, updating caption variable on the fly */}
<input type="file" onChange={handleChange} />
<Button onClick={handleUpload}>
Upload
</Button>
</div>
)
}
export default ImageUpload
Firebase.js代码:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/storage';
import "firebase/compat/storage";
const firebaseApp = firebase.initializeApp //
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage().ref();
const serverTimeStamp = firebase.firestore.FieldValue.serverTimestamp;
export { db, auth, storage, serverTimeStamp };
export default db;
您尚未在此文件中导入 Firebase SDK。相反,您可以直接从 firebase.js
本身导出服务器时间戳,如下所示:
const db = firebase.firestore();
// ..
const serverTimestamp = firebase.firestore.Fieldvalue.serverTimestamp;
export { db, serverTimestamp }
然后在需要的地方导入它:
import { serverTimestamp, db } from "./firebase";
db.collection("posts").add({
timestamp: serverTimestamp(),
caption: caption,
imageUrl: url,
username: username,
});