首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么“this”在Promise调用中未定义

为什么“this”在Promise调用中未定义
EN

Stack Overflow用户
提问于 2018-06-08 01:47:14
回答 2查看 3.9K关注 0票数 5

我不明白是怎么回事

代码语言:javascript
复制
componentDidMount() {
    console.log('componentDidMount');
    //const self = this; 
    let _id = this.props.match.params.id.toUpperCase();

    if (_id != this.state.id.toUpperCase()) {

        axios.get('/data/pricemultifull?fsyms=' + _id + '&tsyms=USD')
            .then(response => {
                // let _currentcoin = { ...resp.data.RAW.BTC.USD, ticker: _id };
                this.setState({ id: _id }); //this == undefined
            });
    }
}

我可以得到一个响应,但是this总是未定义的,并且我无法setState。我使用了一个箭头函数,我认为它的作用域是'this‘到组件级别。我可以通过创建一个新的var并在发出请求之前设置'this'来修复它。不过,我知道this应该可以正常工作。我遗漏了什么?

我的整个组件

代码语言:javascript
复制
import React, { Component } from 'react';
import axios from '../../axios';


class CoinViewer extends Component {

state = {
    coin: {},
    hasLoaded: false,
    id: ''
}

componentDidMount() {
    console.log('componentDidMount');
    //const self = this; 
    let _id = this.props.match.params.id.toUpperCase();

    if (_id != this.state.id.toUpperCase()) {

        axios.get('/data/pricemultifull?fsyms=' + _id + '&tsyms=USD')
            .then( resp => {
                // let _currentcoin = { ...resp.data.RAW.BTC.USD, ticker: _id };
                this.setState({ id: _id });
            });
    }
}

componentWillMount() {

}

componentWillUpdate() {


}

componentDidUpdate() {

}

getCompleteCoinData(_id) {

}


render() {


    return (
        <div>
            CoinViewer Component: {this.state.id} sads
        </div>
    )
}

}

导出默认CoinViewer

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-08 02:47:48

:编辑:哇,下面是真的,但真正的问题是你没有初始化状态。https://reactjs.org/docs/react-component.html#constructor

代码语言:javascript
复制
constructor() {
  super();
  this.state = {
    coin: {},
    hasLoaded: false,
    id: ''
  }
}

你可以像这样使用词法作用域和修复,这是一个保护this的流行模式。

基本上,当您使用来自其他库/API的promises或函数时,您不知道它们在回调函数中设置了什么上下文。

为了使用您想要的上下文,您需要将您需要保存的上下文保存在作用域内的一个变量中,并在_this中引用它,而不是指向上下文this。我建议你读一读“你不知道js”来进一步理解这个概念。

代码语言:javascript
复制
componentDidMount() {
  console.log('componentDidMount');
  const _this = this; 
  let _id = _this.props.match.params.id.toUpperCase();

  if ( _id != _this.state.id.toUpperCase() ) {
    axios.get('/data/pricemultifull?fsyms=' + _id + '&tsyms=USD')
      .then(response => {
        _this.setState({ id: _id }); //this == undefined
      });
  }
}
票数 3
EN

Stack Overflow用户

发布于 2018-06-08 05:08:52

解决方案1:箭头函数..

代码语言:javascript
复制
requestSuccess = (resp) => {
  // let _currentcoin = { ...resp.data.RAW.BTC.USD, ticker: _id };
  this.setState({ id: _id });
}

componentDidMount() {
  console.log('componentDidMount');
  //const self = this; 
  let _id = this.props.match.params.id.toUpperCase();
  if (_id != this.state.id.toUpperCase()) {
     axios.get('/data/pricemultifull?fsyms=' + _id + '&tsyms=USD')
       .then(this.requestSuccess);
  }
}

解决方案2:绑定

代码语言:javascript
复制
componentDidMount() {
  console.log('componentDidMount');
  //const self = this; 
  let _id = this.props.match.params.id.toUpperCase();
  if (_id != this.state.id.toUpperCase()) {
     axios.get('/data/pricemultifull?fsyms=' + _id + '&tsyms=USD')
       .then((resp) => {
          // let _currentcoin = { ...resp.data.RAW.BTC.USD, ticker: _id };
          this.setState({ id: _id });
     }.bind(this));
  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50747307

复制
相关文章

相似问题

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