react jquery ajax 报错:“Cannot read property 'data' of undefined”?

按照官方文档的思路,初始化数据getInitialState => AJAX请求在componentDidMount中更新State => render中渲染数据{this.state}
然后就报错了。
“Cannot read property 'data' of undefined”

import React, {Component} from 'react';
import Jquery from 'jquery';

class StoredNodeChart extends Component {
    getInitialState = () => {
        return {
            test: []
        };
    }
    componentDidMount = () => {
        Jquery.get('over/').done(function (result) {
            let data = JSON.parse(result);
            console.log(data); //成功
            console.log(this); //所有请求信息全部获取
            console.log(data.cifs_num); //成功
            this.setState({
                test: data.cifs_num
            })
        });

    };

    render() {
        return (
            <div>
                Success!
                {this.state.test}
            </div>
        );
    }
}

export default StoredNodeChart;

之后在父级页面引用此组件
看了相似的问题,但是项目构成不同,想不通Cannot read property 'map' of undefined

希望能得到解答,想的头疼?

阅读 6.6k
2 个回答

我觉得你遇到了同步与异步的问题了.
你可以这样尝试调整一下你的代码

Code

async componentDidMount (){
    const response = await fetch(url);
    const data = await response.json();//或者 const data = JSON.parse(response);
    this.setState({
        test: data.cifs_num
        });
    //do something...    
}

希望能帮到你.

从代码看,没发现啥错,没有更详细的报错信息。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题