admin管理员组

文章数量:1305899

I have the following code:

import ReactDom from 'react-dom';
import React from 'react';
import {render} from 'react-dom';
import $ from 'jquery';

class News extends React.Component {
  render () {
    var news = [];
    this.props.news.forEach(function(el, i){
        news.push(<SingleNews key={i} img={el.img} />);
    });
    return (
      <section className="news-wrapper">
          {news}
      </section>
    );
  }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: ''
        }
    }
    mapObject(object, callback) {
      return Object.keys(object).map(function (key) {
        return callback(key, object[key]);
      });
    }
    ponentDidMount () {
      const newsfeedURL = '.json';
      $.get(newsfeedURL, function(result) {
        this.setState({data: JSON.parse(result)});
        console.log(typeof this.state.data.messages);
      }.bind(this));
    }
    render () {
        return (
            <div>
                {Object.keys(this.state.data.messages).map(function(key) {
                    return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
                })}
            </div>
        )
    }
}


ReactDom.render(
  <App />,
  document.getElementById('app')
);

I am trying ti iterate over "this.state.data.messages" to output some data inside the render method.

After typing this "console.log(typeof this.state.data.messages);" I have gathered that "this.state.data.messages" is an object hence the following:

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

however I have the following inside my console:

Uncaught TypeError: Cannot convert undefined or null to object

I have the following code:

import ReactDom from 'react-dom';
import React from 'react';
import {render} from 'react-dom';
import $ from 'jquery';

class News extends React.Component {
  render () {
    var news = [];
    this.props.news.forEach(function(el, i){
        news.push(<SingleNews key={i} img={el.img} />);
    });
    return (
      <section className="news-wrapper">
          {news}
      </section>
    );
  }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: ''
        }
    }
    mapObject(object, callback) {
      return Object.keys(object).map(function (key) {
        return callback(key, object[key]);
      });
    }
    ponentDidMount () {
      const newsfeedURL = 'https://s3-eu-west-1.amazonaws./streetlife-coding-challenge/newsfeed.json';
      $.get(newsfeedURL, function(result) {
        this.setState({data: JSON.parse(result)});
        console.log(typeof this.state.data.messages);
      }.bind(this));
    }
    render () {
        return (
            <div>
                {Object.keys(this.state.data.messages).map(function(key) {
                    return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
                })}
            </div>
        )
    }
}


ReactDom.render(
  <App />,
  document.getElementById('app')
);

I am trying ti iterate over "this.state.data.messages" to output some data inside the render method.

After typing this "console.log(typeof this.state.data.messages);" I have gathered that "this.state.data.messages" is an object hence the following:

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

however I have the following inside my console:

Uncaught TypeError: Cannot convert undefined or null to object

Share Improve this question edited Jan 23, 2019 at 17:04 YakovL 8,36513 gold badges73 silver badges112 bronze badges asked Sep 30, 2016 at 14:57 AessandroAessandro 5,77121 gold badges72 silver badges146 bronze badges 1
  • Is this.state.data.messages === null? – Jed Fox Commented Sep 30, 2016 at 15:08
Add a ment  | 

2 Answers 2

Reset to default 5

The problem here is you are initially setting data as an empty string. In your ponentDidMount you are making the ajax call and since it's async react will still render. Once it renders it's trying to access this.state.data.messages which this.state.data is an empty string so will have no property called messages.

What I would do is have an initial state property called loading and in your render method if this.state.loading === true render something else in the div and if this.state.loading === false && this.state.data.messages actually return what your trying to do now.

Just make sure to set state of loading to false when you parse the JSON response

this.state = {
   data: '',
   loading: true
}
ponentDidMount () {
    const newsfeedURL = 'https://s3-eu-west-1.amazonaws./streetlife-coding-challenge/newsfeed.json';
    $.get(newsfeedURL, function(result) {
        this.setState({
          data: JSON.parse(result),
          loading: false
        });
        console.log(typeof this.state.data.messages);
    }.bind(this));
}
render () {
  let content;
  if (this.state.loading === false && this.state.data.messages) {
    content = {Object.keys(this.state.data.messages).map(function(key) {
      return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
    })}
  } else { 
    content = ''; // whatever you want it to be while waiting for data
  }
  return (
    <div>
      {content}
    </div>
  )
}

You're going to be rendering before that async call returns.

You need to handle the case before there's data. If nothing else you should change the initial state to better match the state you're expecting.

本文标签: javascriptReact iterate over object from json dataStack Overflow