描述
在 componentDidMount 中使用 axio get 获取后端数据,并修改类属性,但提示 count 属性未定义。
错误原因:与 this 的指向有关。
错误代码:
import React, { Component } from 'react';
import axios from 'axios';
// import {Map, Polyline } from 'react-amap';
import * as myData from '../data';
var axio = axios.create({
baseURL : 'http://localhost:8080/phpProjects/'
})
export default class Lines extends Component {
constructor( props ){
super( props );
this.mymap = props.__map__;
this.state = {
times : 0
};
this.count = 0;
//eslint-disable-next-line
this.polylinePath = [
new window.AMap.LngLat(116.41, 39.93),
new window.AMap.LngLat(100.43, 39.91)
];
this.drawAirine = this.drawAirine.bind(this);
}
componentDidMount(){
axio.get('/convey.php',{
params :{
infoT:this.props.timeSetting
}
}).then(function(response){
let data = response.data;
this.count = data["count"]; //错误在这里
})
var line = new window.AMap.Polyline({path:this.polylinePath});
this.mymap.add(line);
}
render() {
return (
null
)
}
}
思考 :
在 axios 中 get 后端数据, this 指向的不是这个类实例。
修改:
在 componentDidMount 声明周期开始,获取指向类的 this 。
import React, { Component } from 'react';
import axios from 'axios';
// import {Map, Polyline } from 'react-amap';
import * as myData from '../data';
var axio = axios.create({
baseURL : 'http://localhost:8080/phpProjects/'
})
export default class Lines extends Component {
constructor( props ){
super( props );
this.mymap = props.__map__;
this.state = {
times : 0
};
this.count = 0;
//eslint-disable-next-line
this.polylinePath = [
new window.AMap.LngLat(116.41, 39.93),
new window.AMap.LngLat(100.43, 39.91)
];
this.drawAirine = this.drawAirine.bind(this);
}
componentDidMount(){
const _this = this; //加上这句!
axio.get('/convey.php',{
params :{
infoT:this.props.timeSetting
}
}).then(function(response){
let data = response.data;
_this.count = data["count"]; //这里的this修改为_this
})
var line = new window.AMap.Polyline({path:this.polylinePath});
this.mymap.add(line);
}
render() {
return (
null
)
}
}