Trying to upload to firebase storage with react. TypeError: Cannot read properties of undefined (reading 'ref')

Trying to upload to firebase storage with react. TypeError: Cannot read properties of undefined (reading 'ref')

下面是代码。控制台日志告诉我它正在正确读取图像,但是 firebase.storage 由于某种原因未定义。

import React from 'react';
import firebase from 'firebase/compat/app';
import "firebase/storage";

function ProfilePic() {


    const [image , setImage] = React.useState('');

    const upload = ()=>{
    if (image == null) return;
        console.log(image);
        const ref = firebase.storage.ref(`images/${image.name}`);
        ref.put(image).on("state_changed" , alert("success") , alert);
        
    }
  
  return (
    <div className="App">
      <center>
      <input type="file" onChange={(e)=>{setImage(e.target.files[0])}}/>
      <button onClick={upload}>Upload</button>
      </center>
    </div>
  );
}

export default ProfilePic;

您需要导入旧的命名空间库才能按预期方式使用它。

import "firebase/compat/storage";

通过使用 "firebase/storage",您最终需要导入现代模块化 SDK。

您还需要使用调用 firebase.storage() 来获取其实例而不是命名空间:

const ref = firebase.storage().ref(`images/${image.name}`);