【问题标题】:Why am I getting a "this2" is undefined?为什么我得到“this2”未定义?
【发布时间】:2019-10-31 12:41:04
【问题描述】:

我认为这与在某处绑定 this 以及我试图迭代一个对象的事实有关。在这段代码中,我可以看到响应是有效的,我只是收到this.setState 行的错误:_this2.setState is not a function.

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

相比之下,这段代码工作得很好,我猜是因为没有循环吗?

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

【问题讨论】:

    标签: javascript function react-native scope this


    【解决方案1】:

    function 语句定义的函数中,this 不会引用上层函数作用域,因为在 JavaScript 中,每个函数在定义时都会创建自己的作用域。如果您使用由箭头函数表示法定义的函数,它将保留范围。

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

    还有here,您可以阅读更多关于箭头函数表示法的信息。

    【讨论】:

    • 感谢您的回复。那么我需要更改映射的格式吗?使用箭头?
    • @MattTakao 我的推荐对你有帮助吗?
    • 好的,非常感谢!箭头函数解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2021-03-24
    • 2015-03-23
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多