簡體   English   中英

為什么'這個'在Promise調用中未定義

[英]Why 'this' is undefined inside a Promise call

我不明白發生了什么

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應該是有效的。 我錯過了什么?

我的整個組件

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

:編輯哇,下面有點真實,但真正的問題是你沒有初始化狀態。 https://reactjs.org/docs/react-component.html#constructor

constructor() {
  super();
  this.state = {
    coin: {},
    hasLoaded: false,
    id: ''
  }
}

您可以使用詞法作用域並像這樣修復,這是一種保護this的流行模式。

基本上,當你使用來自其他庫/ API的promises或函數時,你不知道他們在回調函數中設置了它們的上下文。

為了使用你想要的背景下,挽留你需要保存在范圍內的變量的背景和引用它有_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
      });
  }
}

解決方案1:箭頭功能..

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:綁定

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

使用React.js時,您可能遇到了如何從promise中訪問問題的問題。在promise中有多個解決方案來解析此引用。 舊的方法是設置self = this reference雖然這樣可行,但推薦的解決方案,更符合ES6,將在這里使用箭頭函數:

class Component extends React.Component { 
  componentDidMount() {
    let component = this;
    axios.get('http://…').then(function(data) {
      component.setState( { name: data.blah } );
    });
  }
}

如上所述,箭頭語法是一種更智能的方法,允許使用它來引用React.Component類,如下所示:

class Component extends React.Component { 
  componentDidMount() {
    axios.get('http://…').then(data => {
      this.setState( { name: data.blah } );
    });
  }
}

請注意,我們使用data => {// body}而不是使用function(data){// body},在這種情況下,此引用將不會返回promise實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM