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

时间:2019-02-05 21:53:56

标签: react-native amazon-s3 this setstate aws-amplify

  • 第一个调用(Storage.list('s3存储桶路径'))返回键列表。
  • 对于每个键,我进行第二次调用(Storage.get('key')),该调用返回一个URL
  • 在第一个和第二个API调用中,我console.log并获取了每个所需的正确数据。
  • this.setState可以在第一个API调用中完美运行,但不能在第二个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

谢谢!

1 个答案:

答案 0 :(得分:1)

body, html {background-color: #fff; margin: 0; padding: 0;} table {border-collapse: collapse;} td {border: #aaa dashed 2px; height: 3.3in; padding: .1in; vertical-align: top; width: 2.3in;} span {font-family: Arial; font-size: 24px;} @media footer {tbody {page-break-after: right; break-after: right;}} 的值在this内部丢失了

您可以尝试

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

在代码中显示

this

您可以在下面的链接中了解更多信息,但是我将其要点放在这里。

  

componentDidMount () { const that = this; // now call setState like this that.setState(...) } 始终是调用该方法的对象。但是,当   将方法传递给this时,您没有调用它!方法   将存储在某个地方,稍后再从那里调用。

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