Man*_*ano 4 fetch setstate firebase reactjs
我正在尝试从 Firebase 存储中获取所有图片。
使用 _loadImages 函数进行提取工作正常,但未显示提取的图像。
我对 React 和 React Native 有同样的问题。
我几天以来一直在尝试,但它只是没有重新渲染图像。
任何人都知道如何重新渲染获取的图像?
import React, { Component } from 'react';
import Firebase from '../functions/Firebase'
class Images extends Component {
constructor(props) {
super(props)
Firebase.init();
this.state = {
imageUrl: "",
imageArray: [
"https://images.unsplash.com/photo-1571831284707-b14ca2e0da5f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"https://images.unsplash.com/photo-1494537176433-7a3c4ef2046f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"https://images.unsplash.com/photo-1579170130266-b77007d32ab5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
"https://images.unsplash.com/photo-1565047946982-5ca5149ce14c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
],
loading: false,
}
}
_loadImages = () => {
const imageArray = []
var storage = Firebase.storage
var storageRef = storage.ref()
var listRef = storageRef.child("images/")
listRef.listAll().then((res) => {
res.items.map((itemRef) => {
var urlFB = itemRef.name
var getPictureURL = 'images/'.concat(urlFB)
var starsRef = storageRef.child(getPictureURL)
starsRef.getDownloadURL().then((url) => {
imageArray.push(url)
})
})
})
this.setState({ imageArray })
}
_localLoadImages = () => {
this.setState({ loading: true })
this._loadImages()
this.setState({ loading: false })
}
handleUpload = (e) => {
e.preventDefault();
}
render() {
let imageUrlArray = this.state.imageArray
const images = imageUrlArray.map((item, i) => {
return (
<img
className="SingleImage"
src={item}
key={item}></img>
)
})
return (
<div className="Images" >
{images}
<button type='button' onClick={() => this._localLoadImages()}>Load Images!</button>
</div >
);
}
}
Run Code Online (Sandbox Code Playgroud)
您将其设置为异步函数执行完成之前的状态。
_loadImages = () => {
const imageArray = []
var storage = Firebase.storage
var storageRef = storage.ref()
var listRef = storageRef.child("images/")
listRef.listAll().then((res) => {
res.items.map((itemRef) => {
var urlFB = itemRef.name
var getPictureURL = 'images/'.concat(urlFB)
var starsRef = storageRef.child(getPictureURL)
starsRef.getDownloadURL().then((url) => {
imageArray.push(url)
this.setState({ imageArray })
})
})
})
}
Run Code Online (Sandbox Code Playgroud)
或与async/await,
_loadImages = async () => {
const imageArray = []
const storage = Firebase.storage
const storageRef = storage.ref()
const listRef = storageRef.child("images/")
const list = await listRef.listAll();
list.items.map((itemRef) => {
var urlFB = itemRef.name
var getPictureURL = 'images/' + urlFB;
var starsRef = storageRef.child(getPictureURL)
const url = starsRef.getDownloadURL();
imageArray.push(url);
});
this.setState({ imageArray });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |