我正在制作一个应用程序,它从远程来源获取一系列新闻项目并将它们显示在页面上。
我有端点,可以成功调用,由控制台日志证明,使用$.getJSON(). 我将此调用置于父组件中,因为子组件将需要使用数据。
但是,当我将此数据传递给子组件时,会出现控制台错误:
Uncaught TypeError: Cannot read property 'headline' of undefined
这是因为 React 甚至在数据传入之前就尝试渲染组件。这让我觉得我应该首先在componentDidMount.
为了解决这个问题,我在子组件上设置了一个方法,如果props存在则返回标题:
getHeadline: function () {
if(this.props.newsItems){
return this.props.newsItems.headline
} else {
return null
}
},
这感觉有点令人讨厌。有没有更好的方法,或者我的代码中遗漏了什么?
var BigStory = React.createClass({
getHeadline: function () {
if(this.props.newsItems){
return this.props.newsItems.headline
} else {
return null
}
},
render: function () {
console.log('props:', this.props);
console.log('newsItems:', this.props.newsItems);
return (
<div className="big-story col-xs-12">
<div className="col-sm-5">
<h1>{this.getHeadline()}</h1>
<p>Placeholder text here for now.</p>
<p>time | link</p>
</div>
<div className="col-sm-7">
<img src="http://placehold.it/320x220" alt=""/>
</div>
</div>
);
}
});
var Main = React.createClass({
getInitialState: function () {
return {
newsItems: []
}
},
componentDidMount: function () {
this.getNewsItems();
},
getNewsItems: function () {
$.getJSON('http://www.freecodecamp.com/news/hot', (data) => {
console.log('data sample:', data[0]);
this.setState({newsItems: data})
})
},
render: function () {
return (
<div className="container">
<div className="main-content col-sm-12">
<div className="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12">
<BigStory newsItems={this.state.newsItems[0]}/>
</div>
</div>
</div>
);
}
});