循环访问JSON对象的条目并通过反应状态,获取状态未定义'

时间:2016-09-28 17:55:45

标签: javascript json reactjs get

请原谅我是否偏离目标,但我试图将组件的状态设置为json对象,以便我可以使用该组件进行渲染。

以下是我的组件内部的内容:

render: function() {
    this.serverRequest = $.get(this.props.source, function (data) {
        this.state.content = $.parseJSON(data);

    }.bind(this));

    return (
        <div>

            {Object.keys(this.state.content).map(function (key) {
                return <div>Key: {key}, Value: {this.state.content[key]}</div>;
            })}


        </div>
    );

使用此代码,我目前得到:

  

未捕获的TypeError:无法读取属性&#39; state&#39;未定义的

任何人都知道为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

问题是,this内的$.get()不在React的范围内。在render中调用setState()会抛出错误。以下内容应该有所帮助...

var App = React.createClass({
  getInitialState: function() {
    return {
      content: {},
    }
  },

  componentDidMount: function() {
    this.serverRequest()
  },

  serverRequest: function() {
    var _this = this
    $.get(this.props.source, function(data) {
      _this.state.content = $.parseJSON(data);

    })
  },

  render: function() {
    return ( < div >

      {
        Object.keys(this.state.content).map(function(key) {
          return <div > Key: {
            key
          }, Value: {
            this.state.content[key]
          } < /div>;
        })
      }


      < /div >
    );
  }
})
相关问题