reactjs - 无法正确更改 componentDidMount 中的状态

标签 reactjs firebase

我正在使用 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/

相关文章:

javascript - react native : setState did not update immediately

ios - 如何通过 swift ios 中的键值读取子数据或过滤 firebase 数据

firebase - 直接 Firebase 托管到部署在其他区域的 Cloud Functions

java - 如果文档使用大型 Map 字段,则 Firebase Firestore 查询错误

reactjs - 测试库 React 与 Jest

css - 将 Lighten Css 特性嵌入到 Jsx/React

javascript - 导入获取请求?

reactjs - 如何在 React 中抑制 "The tag <some-tag> is unrecognized in this browser"警告?

google-chrome - Firebase 控制台显示完成您的请求时出错

android - 如何检查 Firebase 中的现有数据?