我正在使用 firebase 进行 React 项目。代码如下
var storage = firebase.storage()
var storageRef = storage.ref();
export default class WallPics extends Component {
constructor(props){
super(props)
this.state={
images : []
}
}
componentWillMount(){
var imgArr=[]
storageRef.listAll()
.then(allPics=>{
allPics.items.forEach(function (picRef){
picRef.getDownloadURL()
.then(function (url){
imgArr.push(
<img src={url} alt="pics" />
)
})
})
this.setState({
images : imgArr
})
})
}
render() {
return (
<div>
{this.state.images}
</div>
)
}
}
在上面的代码中,我从 Firebase 存储中获取所有图片引用,并将图片下载 URL 附加到 imgArr
。将所有 URL 附加到 imgArr
后我想更改状态。但是这里 this.setState
变得空 imgArr
。但是我想用带有图片的 imgArr
更改状态值下载网址。我现在该怎么做?
最佳答案
我不建议你直接将组件放入状态,根据React官方文档here :
State should contain data that a component's event handlers may change to trigger a UI update.
它还明确指出组件不应该进入状态:
this.state should only contain the minimal amount of data needed to represent your UI's state. As such, it should not contain:
React components: Build them in render() based on underlying props and state.
因此,我建议您首先将 fetch 操作提取到一个单独的函数中,以便更好地阅读,并设置您需要声明的 url,而不是组件。
fetchPics = async() => {
const allPics = await storageRef.listAll();
const allUrls = await allPics.items.map(picRef => picRef.getDownloadURL());
// here I use async, you might also use promise.all()
// as stated in @Alexandr Zavalii's answer
this.setState({ images : allUrls })
}
componentDidMount() {
this.fetchPics();
}
最后,使用渲染函数中的 url 渲染组件。
render() {
return (
<div>
{this.state.images.map(url => <img src={url} alt="pics" />)}
</div>
)
}
关于reactjs - 无法正确更改 componentDidMount 中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60108854/