storageRef.child не является функцией в firebase

Возникли проблемы с загрузкой файлов в Firebase с помощью react-firebase-file-uploader. пакет.

Получена ошибка: Uncaught (in promise) TypeError: storageRef.child is not a function

Во-первых, firebase импортируется в мой GatsbyJS Layout.js в componentDidMount как

Layout.js

componentDidMount() {
  const app = import('firebase/app');
  const auth = import('firebase/auth');
  const database = import('firebase/firestore');
  const storage = import('firebase/storage');

  Promise.all([app, auth, database, storage]).then(values => {
    const firebase = getFirebase(values[0]);
    !this.isCancelled && this.setState({ firebase });
  });
}

Затем firebase добавляется как props, используя React.createContext для передачи functions компонентам как

FirebaseContext.js

const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
  <FirebaseContext.Consumer>
    {firebase => <Component {...props} firebase={firebase} />}
  </FirebaseContext.Consumer>
);

export default FirebaseContext;

Внутри компонента firebase мы используем onboardStorage как функцию, содержащую this.storage как

Firebase.js

class Firebase {
  constructor(app) {
    app.initializeApp(config);

    /* Firebase APIs */
    this.app = app;
    this.storage = app.storage();

  // *** Storage API ***
  onboardStorage = () => this.storage;
}

let firebase;

function getFirebase(app, auth, database, storage) {
  if (!firebase) {
    firebase = new Firebase(app, auth, database, storage);
  }

  return firebase;
}

export default getFirebase;

Который затем передается компоненту FileUploader в моем компоненте формы как

Form.js

<FileUploader
  accept="image/*"
  name="avatar"
  filename="operator_accreditation"
  storageRef={() => firebase.onboardStorage().ref(`${uid}/files`)}
  onUploadStart={this.handleUploadStart}
  onUploadError={this.handleUploadError}
  onUploadSuccess={this.handleUploadSuccess}
  onProgress={this.handleProgress}
/>

каждая из функций дескриптора в Form.js выглядит следующим образом

    handleUploadStart = () =>
    this.setState({
      operatorAccreditationIsUploading: true,
      operatorAccreditationProgress: 0
    });

  handleProgress = operatorAccreditationProgress =>
    this.setState({ operatorAccreditationProgress });

  handleUploadError = error => {
    this.setState({ operatorAccreditationIsUploading: false });
    console.error(error);
  };

  handleUploadSuccess = filename => {
    const { firebase, uid } = this.props;
    this.setState({
      operatorAccreditation: filename,
      operatorAccreditationProgress: 100,
      operatorAccreditationIsUploading: false
    });
    const storageOperatorAccreditation = firebase.onboardStorage();
    storageOperatorAccreditation
      .ref(`${uid}/files`)
      .child(filename)
      .getDownloadURL()
      .then(url => this.setState({ operatorAccreditation: url }));
  };

const uid это auth.uid

Добавление сообщения console указывает на то, что ни одно из них не срабатывает при загрузке файла.

Ошибка возникает после выбора файла, указывая на то, что проблема связана с storageRef из FileUploader. Что я сделал не так, чтобы получить Uncaught (in promise) TypeError: storageRef.child is not a function?


person Darren    schedule 17.01.2019    source источник


Ответы (1)


У меня просто была аналогичная проблема. Проблема в том, что вы передаете функцию как свойство storageRef вашему FileUploader. Вместо этого вы должны передать объект storageRef напрямую следующим образом:

<FileUploader
  accept="image/*"
  name="avatar"
  filename="operator_accreditation"
  storageRef={firebase.onboardStorage().ref(`${uid}/files`)}
  onUploadStart={this.handleUploadStart}
  onUploadError={this.handleUploadError}
  onUploadSuccess={this.handleUploadSuccess}
  onProgress={this.handleProgress}
/>
person leiropi    schedule 12.03.2019