【问题标题】:Can't access this.setState inside 2nd API call in nested calls (AWS Amplify Storage API) (React Native)无法在嵌套调用的第二个 API 调用中访问 this.setState (AWS Amplify Storage API) (React Native)
【发布时间】:2019-06-29 19:35:26
【问题描述】:
  • 第一次调用 (Storage.list('s3 bucket path')) 返回一个键列表。
  • 对于每个键,我都会进行第二次调用 (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)
          })
      }

控制台:

  • 我尝试从 componentDidMount 外部的箭头函数进行调用,但仍然无法访问 this.setState

谢谢!

【问题讨论】:

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


    【解决方案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?

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 2022-01-11
      • 2022-07-03
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多