theJuls theJuls - 2 months ago 7
React JSX Question

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

Please forgive if I am way off target, but I am trying to set a component's state to a json object, so that I can render it with the component.

Here is what a currently have inside my component:

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>
);


With this code I currently get:


Uncaught TypeError: Cannot read property 'state' of undefined


Anyone have any insight as to why this isn't working?

Answer

The problem is, the this inside the $.get() is not in the React's scope. And calling setState() inside render will throw an error. The following should help...

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 >
    );
  }
})
Comments