首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我得到一个"this2“是未定义的?

为什么我得到一个"this2“是未定义的?
EN

Stack Overflow用户
提问于 2019-06-18 06:07:06
回答 1查看 746关注 0票数 0

我假设这与某个地方的绑定this有关,并且我正试图迭代一个对象。在这段代码中,我可以看到响应是有效的,我只是得到了一个关于this.setState行的错误:_this2.setState is not a function.

代码语言:javascript
运行
复制
componentDidMount() {
    console.log('MatchesScreen: ', Object.keys(this.props))
    Object.keys(this.props.profile.profile.matches).map(function(username, keyIndex) {
      console.log('match', username)
      url = 'https://xxxxx.execute-api.us-west-2.amazonaws.com/prod/profile?username=' + username
      fetch(url, {
        method: 'GET',
      })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({isLoading: false})
        this.props.updateMatches({matches: responseJson})
      })
      .catch((error) =>{
        console.error(error);
      })
    })
  }

相比之下,我认为这段代码工作得很好,因为没有发生循环?

代码语言:javascript
运行
复制
componentDidMount() {

    Auth.currentAuthenticatedUser({
        bypassCache: false
    }).then(user => {
      username = 'username=' + user.username
      this.setState({username: user.username})
      url = 'https://xxxxxxx.execute-api.us-west-2.amazonaws.com/prod/profile?' + username
      fetch(url, {
        method: 'GET',
      })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
          age: responseJson.basic_info.age.toString(),
          height: responseJson.basic_info.height,
          promptQuestion: responseJson.prompt_question,
        })
      })
      .catch((error) =>{
        console.error(error);
      });
    })
    .catch(err => console.log('EditProfileScreen: error getting user: ', err))
  }
EN

回答 1

Stack Overflow用户

发布于 2019-06-18 06:15:50

在由function语句定义的函数中,this不会引用上层函数作用域,因为在JavaScript中,每个函数在定义时都会创建自己的作用域。如果使用由定义的函数和箭头函数符号,它将保持作用域不变。

您可以阅读有关函数作用域here的更多信息。

here你可以阅读更多关于箭头函数符号的内容。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56639462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档