简体   繁体   English

类型错误:无法读取未定义的 Firebase 存储反应的属性“ref”

[英]TypeError: Cannot read property 'ref' of undefined Firebase-storage react

I'm making an app, user can upload files and store in firebase storage.我正在制作一个应用程序,用户可以上传文件并存储在 firebase 存储中。
When I click upload then keep getting error "TypeError: Cannot read property 'ref' of undefined"当我点击上传然后不断收到错误“类型错误:无法读取未定义的属性'ref'”
firebase config looks correct. firebase 配置看起来正确。
Any helps, tips much appreciated!任何帮助,非常感谢提示!

Here is my code这是我的代码

import React from "react";
import firebase from "./services/firebase";
import storage from "./services/firebase";

export class Upload extends React.Component {
  constructor(props) {
    super(props);
    this.state = { image: null, url: "" };
    this.handleUpload = this.handleUpload.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    console.log(event.target.files[0]);
    if (event.target.files[0]) {
      const image = event.target.files[0];
      this.setState({ image: image });
    }
  }

  handleUpload() {
    const image = this.state.image;
    console.log(image);
    const uploadTask = firebase.storage.ref(`images/${image.name}`).put(image);
    uploadTask.on("state_changed", () => {
      firebase.storage
        .ref("images")
        .child(image.name)
        .getDownloadURL()
        .then(url => {
          this.setState({ url });
        });
    });
  }

  render() {
    console.log(this.state.image);
    return (
      <div className="upload">
        <h2 className="title">Upload content for your project</h2>
        <div className="container">
         <label>Photo</label>
                <img src="/imgs/P.png" alt="photo" />
                <input
                  type="file"
                  accept=".jpg, image/png, .jpeg, .gif"
                  onChange={this.handleChange}
                />
                <button onClick={this.handleUpload}>Upload</button>
        </div>
     </div>
    );
  }
}

Here is "./services/firebase" file这是“./services/firebase”文件


import firebase from "firebase/app";
import "firebase/database";
import "firebase/auth";
import "firebase/storage";
import "firebase/firestore";
import config from "./config";


const firebaseConfig = config;


firebase.initializeApp(firebaseConfig);


const database = firebase.database();


const listenTo = (dataToListenTo = "", callbackFunction = () => {}) => {
  const databaseRef = database.ref(dataToListenTo);

  databaseRef.on("value", snapshot => {
    callbackFunction(snapshot);
  });

  return databaseRef;
};


const writeTo = (dataToWriteTo = "", value) => {
  const databaseRef = database.ref(dataToWriteTo);

  databaseRef.push(value);
};


const update = (keyToUpdate = "", value) => {
  const databaseRef = database.ref(keyToUpdate);

  databaseRef.update(value);
};


const remove = (keyToUpdate = "") => {
  const databaseRef = database.ref(keyToUpdate);

  databaseRef.remove();
};


const getCurrentUser = () => {
  return firebase.auth().currentUser;
};


const isLoggedIn = () => {
  if (firebase.auth().currentUser) {
    return true;
  }

  return false;
};

const signIn = (email, password) => {
  return firebase.auth().signInWithEmailAndPassword(email, password);
};


const onLoginChange = (callbackFunction = () => {}) => {
  const authRef = firebase.auth().onAuthStateChanged(user => {
    callbackFunction(user);
  });

  return authRef;
};


const signOut = () => {
  return firebase.auth().signOut();
};

const createUser = (email, password) => {
  return firebase.auth().createUserWithEmailAndPassword(email, password);
};

export default {
  writeTo,
  listenTo,
  update,
  remove,
  getCurrentUser,
  isLoggedIn,
  signIn,
  onLoginChange,
  signOut,
  createUser
};

What am I doing wrong?我究竟做错了什么?

storage() is a method not a property, therefore in your code you should use the following : storage()是一种方法而不是属性,因此在您的代码中您应该使用以下内容:

firebase.storage().ref(`images/${images.name}`)


firebase.storage().ref("images")

Check here for more info:在这里查看更多信息:

https://firebase.google.com/docs/reference/js/firebase.storage.html https://firebase.google.com/docs/reference/js/firebase.storage.html

Hope this can share another perspective and maybe order of operations helps, still learning myself as you can see by my account.希望这可以分享另一个观点,也许操作顺序会有所帮助,正如您在我的帐户中看到的那样,仍在学习自己。

I solved this simply by moving my "const userUid = firebase.auth.currentUser!.uid down into the function it was being used in like below:我只是通过将我的“const userUid = firebase.auth.currentUser!.uid”移到它正在使用的函数中来解决这个问题,如下所示:

const userUid = auth.currentUser.uid;

const handleSubmit = (e: any) => {
    e.preventDefault();
    setLoader(true);
    dbuser
      .collection("User Data")
      .doc(userUid)
      .set({
        name: name,
        email: email,
        message: message,
      })
      .then(() => {
        alert(
          "Congratulations"
        );
        setLoader(false);
      })
      .catch();
    // alert(error.message);
    setLoader(false);

to

  const handleSubmit = (e: any) => {
    const userUid = auth.currentUser!.uid;
    e.preventDefault();
    setLoader(true);
    dbuser
      .collection("User Data")
      .doc(userUid)
      .set({
        name: name,
        email: email,
        message: message,
      })
      .then(() => {
        alert(
          "Congratulations, it will take 1 business day to review and approve your seller profile"
        );
        setLoader(false);
      })
      .catch();

    // alert(error.message);
    setLoader(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:无法读取未定义的属性“ref” - TypeError: Cannot read property 'ref' of undefined React&Firebase-未捕获的TypeError:无法读取未定义的属性&#39;setState&#39; - React & firebase- uncaught TypeError: Cannot read property 'setState' of undefined React JS,Firebase,TypeError:无法读取未定义的属性“initializeApp” - React JS, Firebase, TypeError: Cannot read property 'initializeApp' of undefined AngularFire 存储 - 类型错误:无法读取未定义的属性 'then' - AngularFire Storage - TypeError: Cannot read property 'then' of undefined TypeError:无法读取未定义的firebase和vuex的属性“ 0” - TypeError: Cannot read property '0' of undefined firebase and vuex FIREBASE警告:TypeError:无法读取未定义的属性“ then” - FIREBASE WARNING: TypeError: Cannot read property 'then' of undefined 类型错误:无法读取未定义的属性“长度”- Firebase - TypeError: Cannot read property 'length' of undefined - Firebase Firebase TypeError:无法读取未定义的属性“ ac” - Firebase TypeError: Cannot read property 'ac' of undefined Firebase TypeError:无法读取未定义的属性“val” - Firebase TypeError: Cannot read property 'val' of undefined Cloud Firestore:TypeError:无法读取未定义的属性“ ref” - Cloud Firestore: TypeError: Cannot read property 'ref' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM