TypeError:$ .ajax请求的this.state为null

时间:2016-10-06 15:50:20

标签: javascript ajax reactjs

var Movie = React.createClass({
  getInitialState: function() {
    $.ajax({
      url: "getjsonarray.php",
      dataType: 'json',
      method: "POST",
      data: {
        startpoint: 0,
        perpage: 2
      },
      success: function(data) {
        this.setState({
          json: data
        }, function() {
        }.bind(this));
      }.bind(this),
    });
    return null;
  },
  render: function() {
    return (
      <div>
        {
          this.state.json.map(function(object, i){
            return (
              <div key={i}>                          
                <h1>Movie {i}</h1>
                <h2>Genre {i}</h2>
              </div>  
            );
          })
        }
      </div>
    );
  }
});
ReactDOM.render(<Movie/>, document.getElementById('container'));

在这里,我试图从后端获取json数组,通过反应js迭代数组。但我只得到这个错误,

  

TypeError:this.state为null

有没有办法用ajax responcejson数组返回值?

这是我从后端得到的,

[{"id":"1","image":"http:\/\/images.prd.mris.com\/image\/V2\/1\/Yu59d899Ocpyr_RnF0-8qNJX1oYibjwp9TiLy-bZvU9vRJ2iC1zSQgFwW-fTCs6tVkKrj99s7FFm5Ygwl88xIA.jpg","price":"$1,975,000 ","address":"609 W Gravers Ln","area":"4,820 SqFt","beds":"5","baths":"5","desc":"Situated between fairmount park and the prestigious philadelphia cricket club, this beautiful 2+ acre property is truly","subdesc":"Courtesy of HS Fox & Roach-Chestnut Hill Evergreen"},{"id":"2","image":"http:\/\/images.prd.mris.com\/image\/V2\/1\/vGoNjc2jHGb87GlnnDQlf6LxeOUgIOn0bL6Wvn1nEnig2Ntq6W7xN5cOQBZZeNxl9O42DOkHUw0LNnj1ZB2KHA.jpg","price":"$1,500,000","address":"1220-32 N Howard St","area":"4,900 SqFt","beds":"1","baths":"1","desc":"A once in a lifetime opportunity to own a unique live \/ work space in one of philadelphia's most popular neighborhoods.","subdesc":"Courtesy of ll Banker Preferred-Philadelphia"}]

3 个答案:

答案 0 :(得分:1)

这里的问题是ajax是异步的,所以getInitialState首先出现,然后直接进行渲染,api调用仍然在传输中,并且在收到响应之前你实际上并没有设置状态。我建议将json的初始状态设置为空数组,然后添加一个componentDidMount函数来执行ajax请求并更新json的状态。

getInitialState: function() {  
    return {
      json: []
    }
},             

componentDidMount: function() {
   $.ajax({
        url: "getjsonarray.php",
        dataType: 'json',
        method: "POST",
        data : {startpoint: 0, perpage: 2},
        success: function(data) {  
          this.setState({json: data}, function(){

          }.bind(this));

        }.bind(this),
    });
},

在我自己的应用程序中,每当我有一个依赖于api调用来获取其数据的组件时,我会向我的组件添加一个加载状态,该加载状态最初为true,然后为true时我会渲染不同的或某种类型的东西旋转器然后,一旦api调用完成,它将把加载状态设置为false并更新数据状态。

答案 1 :(得分:0)

您的问题是您的代码会破坏该组件的生命周期。你应该  1.进行AJAX调用,一旦获得所需的值,就创建组件。  2.创建组件,然后使用AJAX响应中的值更新它。

答案 2 :(得分:0)

您应该在组件的componentDidMount生命周期方法中获取服务器数据/响应。你的代码可以是这样的

    var Movie = React.createClass({

    getInitialState: function () {
      this.state = { json: [] };
    },

    componentDidMount: function () {
      var self = this;

      $.ajax({
        url: "getjsonarray.php",
        dataType: 'json',
        method: "POST",
        data: {
          startpoint: 0,
          perpage: 2
        },
        success: function (response) {

          /* okay, now re-render component with received response */
          self.setState({
            json: response
          });

        }
      });

    },

    render: function () {
      /* in initial render json array is empty */
      var json = this.state.json;

      return (
        <div>
          {
            json.map(function (object, i) {
              return (
                <div key={i}>
                  <h1>Movie {i}</h1>
                  <h2>Genre {i}</h2>
                </div>
              );
            })
          }
        </div>
      );
    }
  });

  ReactDOM.render(<Movie/>, document.getElementById('container'));