Добавить массив изображений в хранилище Firebase и базу данных в реальном времени, используя React JS - PullRequest
0 голосов
/ 18 февраля 2019

Я пытаюсь отправить массив локальных изображений в хранилище Firebase и в мою базу данных.Изображения выводятся в моей схеме базы данных json, но в хранилище ничего не отображается, и я получаю следующие ошибки ниже.Есть мысли?

Ошибка: enter image description here

Схема JSON базы данных:

{
  "users" : {
    "XhLxS1KUS8UyHjsuHYrEuyipQX53" : {
      "Email" : "ssssss@gmail.com",
      "code" : "bob",
      "image1" : {
        "id" : "223d7f60-331b-11e9-b680-6b36b34d4cc6",
        "url" : "holder1.png"
      },
      "image2" : {
        "id" : "223da670-331b-11e9-b680-6b36b34d4cc6",
        "url" : "holder2.png"
      },
      "image3" : {
        "id" : "223da671-331b-11e9-b680-6b36b34d4cc6",
        "url" : "holder3.png"
      },
      "location" : "fl"
    }
  }
}

Реагировать JS:

const images = [
  {
    id: uuid(),
    url: `holder1.png`
  },
  {
    id: uuid(),
    url: `holder2.png`
  },
  {
    id: uuid(),
    url: `holder3.png`
  }
];


class Register extends Component {
  state = {
    email: '',
    password: '',
    code: 'bob',
    location: 'fl',
    image: null,
    url: '',
    error: null,
    arr: images,
  };


  handleInputChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleChange = e => {
    if (e.target.files[0]) {
      const image = this.state.arr;
      this.setState(() => ({ image }));
      console.log(image)
    }
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const { email, password, image, url } = this.state;

    const storageRef = storage.ref(`images/`);
    this.state.image.map((file, index) => {
      storageRef
        .child(`${file.url}`)
        .getDownloadURL().then(url => {
          this.setState({ url }); <---Should I set state?
        })
    });

    firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        firebase
        .database()
        .ref('users/' + user.user.uid)
        .set({
          Email: user.user.email,
          code:  this.state.code,
          location:  this.state.location,
          image1:  images[0],
          image2:  images[1],
          image3:  images[2]
        })
        //console.log(this.state.url)
        this.props.history.push('/');
      })
      .catch((error) => {
        this.setState({ error: error });
      });
  };
....

Это работает для одного изображения в хранилище:

React JS:

class Register extends Component {
  state = {
    email: '',
    password: '',
    code: 'bob',
    location: 'fl',
    image: null,
    url: '',
    error: null,
  };


  handleInputChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleChange = e => {
    if (e.target.files[0]) {
      const image = e.target.files[0];
      this.setState(() => ({image}));
    }
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const { email, password, image, url } = this.state;
    const uploadTask = storage.ref(`images/${image.name}`).put(image);

    uploadTask.on('state_changed', () => {
      storage.ref('images').child(image.name).getDownloadURL().then(url => {
          console.log(url);
          this.setState({url});
      })
    });

    firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        firebase
        .database()
        .ref('users/' + user.user.uid)
        .set({
          Email: user.user.email,
          code:  this.state.code,
          location:  this.state.location,
          image:  this.state.url
        })
        this.props.history.push('/');
      })
      .catch((error) => {
        this.setState({ error: error });
      });
  };
...

1 Ответ

0 голосов
/ 18 февраля 2019

Как я прокомментировал ваш предыдущий вопрос :

Вам необходимо записать URL-адрес базы данных из обратного вызова на getDownloadUrl().Так что, где вы сейчас звоните this.setState({url});, звоните что-то вроде firebase.database().ref('users/' + user.user.uid + '/image').set(url); тоже.

Кроме того, насколько я вижу из документации , для UploadTask.on('state_changed' существует три обратных вызова, а третий вызывается после завершения загрузки.

Итак:

uploadTask.on('state_changed', function(snapshot) {
  // handle progress messages here
},(error) => {
  // handle errors here
},() => {
  storage.ref('images').child(image.name).getDownloadURL().then(url => {
      console.log(url);
      this.setState({url});
      firebase.database().ref('users/' + user.user.uid + '/image').set(url);
  })
});
...