我有一种情况,我确定这很常见,但我还没有学会完成它的 react 方式。假设我有这个:
var appView = new React.createClass({
render: function() {
return (
<div>
<SomeSubview/>
</div>
)
}
});
React.render(
React.createElement(appView),
$('#app').get(0)
);
我的问题是我应该如何创建 SomeSubView
react 组件,以便它可以在没有任何数据的情况下正确渲染,然后在数据可用时渲染显示一些数据。我已经设置了 pub/sub 系统,所以我希望能够订阅一个事件并以这种方式将数据获取到 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>
)
}
});
我不知道这是否是 react 组件上的状态或 Prop 的情况?我不知道在渲染函数中放置条件是否是最佳实践?
最佳答案
在您的 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() 来循环标记,就像在大多数渲染示例中一样。
关于javascript - 如何制作一个可以在没有数据的情况下渲染然后用数据渲染的 react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229478/