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

Kai*_*per 5 javascript reactjs

我不明白发生了什么

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
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以得到回复,但this始终未定义,我无法回复setState。我正在使用一个箭头函数,我认为它是组件级别的“this”范围。我可以通过'this'在发出请求之前创建一个新的 var 和设置来修复它。我知道这this应该有效。我错过了什么?

我的整个组件

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>
    )
}
Run Code Online (Sandbox Code Playgroud)

}

导出默认 CoinViewer

Eri*_*ing 3

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

constructor() {
  super();
  this.state = {
    coin: {},
    hasLoaded: false,
    id: ''
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用词法作用域并像这样修复,这是保护this.

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

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

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
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 根据定义,箭头函数显式保留 `this` 的词法范围,因此在传递给 `then` 的回调函数内,`_this === this` 应该为 true。问题来自其他地方(也许是一个坏的转译器?)。 (2认同)