无法在嵌套调用中的第二个 API 调用中访问 this.setState (AWS Amplify Storage API) (React Native)

Can't access this.setState inside 2nd API call in nested calls (AWS Amplify Storage API) (React Native)

我的代码是:

    state = { keyItems: [], urlItems: [] }

    componentDidMount() {
        Storage.list('')
          .then(keyItems => {
            console.log("keyItems: ", keyItems)
            this.setState({ keyItems: keyItems })

            /*for each photo key in the folder..*/
            keyItems.forEach(function(keyItem) {
              /*get the URL*/
              Storage.get(keyItem.key)
                .then(urlItem => {
                  console.log("urlItem: ", urlItem)
                  /*add URL item to state*/
                  /*ANY CALL TO this.setState HERE DOESN'T WORK, i've tried 
                  even simple tests*/
                  this.setState(prevState => ({ urlItems:[...prevState.urlItems, { key: keyItem.key, source: urlItem } ]}))
                })
                .catch(err => {
                  console.log("error fetching photo URL", err)
                })
            })
          })
          .catch(err => {
            console.log("error fetching photos keys", err)
          })
      }

控制台:

谢谢!

this 的值在 .then

中丢失

你可以试试这个

  1. this设置为一个变量
  2. 使用该变量代替 this

在代码中

componentDidMount () {
  const that = this;

  // now call setState like this
  that.setState(...)

}

您可以在下面的 link 阅读更多相关信息,但我已将它的一般要点放在这里。

this is always the object the method is called on. However, when passing the method to then(), you are not calling it! The method will be stored somewhere and called from there later.