我有以下代码:
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]);
});
}
componentDidMount () {
const newsfeedURL = 'https://s3-eu-west-1.amazonaws.com/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')
);
我正在尝试迭代“this.state.data.messages”以在渲染方法中输出一些数据。
输入“console.log(typeof this.state.data.messages);”后 我收集到“this.state.data.messages”是一个对象,因此如下:
{Object.keys(this.state.data.messages).map(function(key) {
return <div>Key: {key}, Value: {this.state.data.messages[key]}</div>;
})}
但是我的控制台中有以下内容:
未捕获的类型错误:无法将未定义或空值转换为对象