我有一个非常简单的例子。我对新的反应和ES6都是新手,所以这可能是我身上的愚蠢行为:
App.js:
import React, { Component } from 'react';
import { CampaignListMobile } from './campaign_list_mobile.js'
var campaigns = [
{
id: 1,
name: 'My first testing'
},
{
id: 2,
name: 'My second testing'
}
];
export class App extends Component {
render() {
return (
<CampaignListMobile campaigns={campaigns}/>
);
}
}
campaign_list_mobile.js:
import React, { Component } from 'react';
import { CampaignMobile } from './campaign_mobile.js'
export class CampaignListMobile extends Component {
render() {
let campaigns = [];
let data = this.props.campaigns;
data.forEach(function(campaign){
var html = <li><CampaignMobile /></li>
campaigns.push(html);
}.bind(this));
return (
<ul>
{campaigns}
</ul>
);
}
}
campaign_mobile.js:
import React, { Component } from 'react';
export class CampaignMobile extends Component {
render() {
<h2>Testing</h2>
}
}
这会抛出错误
Uncaught Error: Invariant Violation: CampaignMobile.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
这可能与我如何在 CampaignListMobile
中构建列表有关答案 0 :(得分:3)
你需要返回JSX(目前你的渲染函数只是返回未定义的,即不是有效的ReactComponent):
render() {
return <h2>Testing</h2>;
}
请注意,如果它跨越多行,则需要将其包装在()
。
P.S。您可能不需要在导入中包含.js
扩展名
在这种情况下,您可能会发现使用map和es6 arrow functions清洁工:
render() {
return (
<ul>
{this.props.campaigns.map(campaign => {
return <li><CampaignMobile campaign={campaign} /></li>;
})}
</ul>
);
}
如果您没有为每个key
提供唯一的li
道具,则React会抱怨,因为它无法有效更新列表,因此如果campaign
具有某些独特的属性,那么用那个即。 key={campaign.id}