循环遍历JSON对象's条目并遍历react state,获取'state undefined'

Looping through a JSON object's entries and through react state, getting 'state undefined'

本文关键字:state 遍历 react 获取 undefined JSON 对象 循环      更新时间:2023-09-26

如果我偏离目标,请原谅,但我正试图将组件的状态设置为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>
    );

使用这个代码,我目前得到:

Uncaught TypeError: Cannot read property 'state' of undefined

有人知道为什么这不起作用吗?

问题是,$.get()中的this不在React的范围内。在渲染中调用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 >
    );
  }
})