React: Unhandled Rejection (TypeError): Cannot set property 'count' of undefined 错误修改

描述

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值