我有一个React.js应用程序从HackerNews API中提取前30个故事,并显示页面上的前30个故事。截至目前,我的StoryTop渲染功能显示了从其API中检索单个故事的正确链接,该API也显示在屏幕上。我遇到麻烦的地方是将此链接传递给Story类,我收到错误" src未定义"。
var StoryTop = React.createClass({
getInitialState: function() {
return {
content: []
};
},
componentDidMount: function() {
var src ="https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
$.get(src, function(result) {
var stories = result;
if (this.isMounted()) {
this.setState({
content: stories.slice(0,30)
});
}
}.bind(this));
},
render: function() {
var storyNodes = this.state.content.map(function(item) {
var src ="https://hacker-news.firebaseio.com/v0/item/" + item + "/.json?print=pretty";
return (
<tr key={item}>
<td>
{src}
<Story/>
</td>
</tr>
);
});
return (
<table>
<tbody>
{storyNodes}
</tbody>
</table>
);
}
});
React.render(
<StoryTop />,
newstories
);
var Story = React.createClass({
getInitialState: function() {
return {
by: '',
title: '',
score: '',
url: ''
};
},
componentDidMount: function() {
$.get(src, function(result) {
var story = result;
if (this.isMounted()) {
this.setState({
by: story.by,
score: story.score,
url: story.url,
title: story.title,
});
}
}.bind(this));
},
render: function() {
var divclass = 'indivstory';
var topPClass = 'storytop';
var bottomPClass= 'storybottom';
return (
<div className={divclass}>
<p className={topPClass}> <span></span><img src="./images/uparrow.gif"></img> <span><a href={this.state.url}>{this.state.title} ({this.state.url.replace(/^https?:\/./,'').replace(/\/.*$/,'')}</a>).</span> </p>
<p className={bottomPClass}> {this.state.score} points by {this.state.by} | discuss </p>
</div>
);
}
});
修改编辑: 将var src传递给Story:
var src ="https://hacker-news.firebaseio.com/v0/item/" + item + "/.json?print=pretty";
return (
<tr key={item}>
<td>
{src}
---> <Story link = {src} />
</td>
</tr>
使用&#34;链接&#34;获取故事数据:
componentDidMount: function() {
$.get(this.props.link, function(result) {
var story = result;
答案 0 :(得分:0)
看起来componentDidMount正在调用src但是没有定义src。在本地块范围内。
componentDidMount: function() {
$.get(this.render.src, function(result) {
var story = result; ...