未捕获(承诺)TypeError:未定义是不可迭代的

时间:2020-09-22 06:10:37

标签: reactjs firebase react-native promise setstate

我有此错误:

bundle.js:2066 Uncaught (in promise) TypeError: undefined is not iterable.

我的代码:

firebase.auth().onAuthStateChanged(user => {
  if (user)
  {
    if (user.uid != null)
    {
      let storageRef = firebase.storage().ref("Users/" + user.uid);
      console.log(storageRef)
      storageRef.listAll().then( res => {
        let promises = res.items.forEach( item => item.getDownloadURL() );
    
        Promise.all(promises).then((downloadURLs) => {
            this.setState({ urlImage: downloadURLs });
        })
      })
    }

    console.log(this.state.urlImage)

    const actionPhoto = { type: "TOGGLE_PHOTO", value: this.state.urlImage };
    this.props.dispatch(actionPhoto)

    const actionUid = { type: "TOGGLE_UID", value: user.uid };
    this.props.dispatch(actionUid)

    // On ajoute le nom et la photo du current user
    const actionName = { type: "TOGGLE_NAME", value: user.displayName };
    this.props.dispatch(actionName)

    //this.props.navigation.navigate('Navigation')
}
})

我在foreach(items)中有一项,而ref()的存储火力源很好。

你有个主意吗?

2 个答案:

答案 0 :(得分:1)

问题似乎出在let promises = res.items.forEach( item => item.getDownloadURL());

行中

forEach()函数returns undefined。使用map()函数代替returns the resulting array

let promises = res.items.map( item => item.getDownloadURL() );

答案 1 :(得分:1)

首先,确保您的res对象具有items,并且它必须是一个数组。 然后,将forEach迭代器更改为map,以便它根据您的res.items生成一个新的映射数组。

let promises = res.items.map( item => item.getDownloadURL() );

Promise.all(promises).then((downloadURLs) => {
            this.setState({ urlImage: downloadURLs });
        })