我有一种情况,我确定是很普遍的,只是我还没有学到完成它的反应方式。假设我有这个:
var appView = new React.createClass({
render: function() {
return (
<div>
<SomeSubview/>
</div>
)
}
});
React.render(
React.createElement(appView),
$('#app').get(0)
);
我的问题是我应该如何创建SomeSubView react组件,以便它可以正确呈现而不包含任何数据,然后在可用数据时稍后呈现显示一些数据。我已经设置了发布/订阅系统,所以我希望能够订阅一个事件并以这种方式将数据获取到SomeSubView。 SomeSubView可能看起来像这样:
SomeSubView = new React.createClass({
componentDidMount: function() {
pubsub.subscribe({
callback: function() {
// something the sets the state or a prop of this component
}
});
},
render: function() {
// something that renders properly when
// there is no data and renders the data when there is data
return (
<div></div>
)
}
});
我不能说这是否是反应组件的状态或道具的案例?我不知道将条件放在渲染函数中是否是最佳实践?
最佳答案
在SomeSubView中,只需检查渲染函数中是否有数据,但要返回标记。
像这样:
SomeSubView = new React.createClass({
componentDidMount: function() {
pubsub.subscribe({
callback: function() {
// something the sets the state or a prop of this component
}
});
},
render: function() {
// something that renders properly when
if( this.state.data.length > 0 ){
var data = <li>{this.state.data}</li>;
}
return (
<div>{data}</div>
)
}
});
如果未设置变量数据,React将简单地将其作为不存在的对象传递。
当然,您也可以在状态数据上使用.map()来循环标记,就像大多数渲染示例一样。