【发布时间】:2018-11-17 17:27:54
【问题描述】:
我不明白发生了什么
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
【问题讨论】:
-
我使用相同的方法,但使用了 fetch。它似乎正在工作!
-
您应该能够使用箭头函数访问组件的
this上下文。见这里:stackoverflow.com/questions/41194866/…你能分享你整个组件的代码吗? -
无法重现您的问题,我尝试了与您的代码类似的方法,但它对我有用。 codepen.io/smilesaayush/pen/VdKoJa 如果我在 axios 响应后不使用箭头函数,那么它会报错,否则它可以工作。
-
如果我声明 let self == this 然后 self.setState(...) 它可以工作。对于任何其他公理承诺,我从来不需要这样做。对我来说有点困惑
-
也许可以尝试在每个步骤中记录
this的内容,看看是否符合您的预期。还要验证你是否能够在代码的其他地方使用箭头函数,这样你就知道它不是编译器错误
标签: javascript reactjs