未捕获的TypeError: Cannot read property 'then'在React aja



我是react js的新手。我对在reactjs中加载初始数据有点困惑。我很确定我的ajax调用是工作的,但我不知道如何处理数据和操纵json数据到我的组件。App.js

var React = require('react');
var Actions = require('../actions');
var Store = require('../stores/store');
var Nav =require('./Nav');
var Fakeprofile = require('./Fakeprofile');
var Sidemenu = require('./Sidemenu');
var Bulkmail = require('./Bulkmail');
var store = require('../stores/store');
var api = require('../utils');
function getAppState() {
    return {
    }
}

var App = React.createClass({
   getInitialState:function () {
       return getAppState();
   },
    componentDidMount: function(){
        api.getprofile().then(function(response) {
            console.log(response);
            this.setState({
                data:response
            });
        });
        Store.addChangeListener(this._onChange);
    },
    componentUnmount: function(){
        Store.removeChangeListener(this._onChange);
    },

    render:function () {
        console.log(this.state.data);
        return(
            <div>
                <Nav/>
                <Sidemenu/>
                <Fakeprofile data={this.state.data} />

            </div>
        )
    },
    _onChange: function(){
        this.setState(getAppState());
    }
});
module.exports = App;

Utils.js

var actions = require('./actions');
module.exports = {
  getprofile:function () {
      console.log('Gettinf data');
      var url  = 'http://localhost:3000/api/index';
      $.ajax({
          url:url,
          dataType:'json',
          cache:false,
          success:function success(data) {
              console.log(data);

          }.bind(this),
          error:function error(xhr,status,err) {
              console.log(err);
          }
      })
  }
};

如果定义了jQuery,尝试在$.ajax()之前包含return语句以从getprofile()调用返回jQuery承诺对象

getprofile:function () {
      console.log('Gettinf data');
      var url  = 'http://localhost:3000/api/index';
      // add `return` before `$.ajax()` to return jQuery promise
      // from `getprofile()` call
      return $.ajax({
          url:url,
          dataType:'json',
          cache:false,
          success:function success(data) {
              console.log(data);

          }.bind(this),
          error:function error(xhr,status,err) {
              console.log(err);
          }
      })
  }

在react中使用AJAX对我来说似乎很奇怪,当有react本地Fetch方法来做到这一点时。

这就是我要做的。

getProfile: function() {
    fetch('http://localhost:3000/api/index',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
       });
在App.js中

这就是你的错误所在-你需要在。then.

中返回一个响应。
componentDidMount: function(){
        api.getprofile().then(response => response.json())
        .then( (json => {
            this.setState({
            data: json
        });
    });
}