不能访问嵌套调用(AWS中扩增存储API)this.setState内第二次API调用(阵营母语)

问题描述 投票:0回答:1
  • 第一次调用(Storage.list(“S3存储路径”))返回键的列表。
  • 对于每一个关键,我作出这样的返回URL的第二个电话(Storage.get(“钥匙”))
  • 里面的第一和第二API调用我CONSOLE.LOG,并得到正确的数据我需要为每个。
  • this.setState完美的作品第一API调用里面,但是它没有第二个内。

我的代码是:

    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)
          })
      }

控制台:Console

  • 我试图使从componentDidMount外箭头函数的调用,但仍无法访问this.setState

谢谢!

react-native amazon-s3 this setstate aws-amplify
1个回答
1
投票

this的值迷路.then

你可以试试这个

  1. 设置this一个变量
  2. 使用该变量,而不是this

这在码

componentDidMount () {
  const that = this;

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

}

您可以通过以下链接阅读更多关于它,但是我在这里把它的一般要点。

this总是方法被调用的对象。然而,传递方法then()的时候,你是不是调用它!该方法将存储在某个地方,并从那里以后调用。

Why is 'this' undefined inside class method when using promises?

© www.soinside.com 2019 - 2024. All rights reserved.