如何防止组件在加载数据之前呈现
How can I prevent a component from rendering before data is loaded?
我正在等待道具从名为GetDealersStore
的存储中出现,我获取数据的方式是通过一个操作,我这样做:
componentWillMount () { GetDealersActions.getDealers(); }
我已经测试了应用程序和componentWillMount()
在初始渲染之前运行,我有这个
let dealerInfo;
if (this.state.dealerData) {
dealerInfo = this.state.dealerData.dealersData.map((dealer) => {
return (<div>CONTENT</div>);
})
} else {
dealerInfo = <p>Loading . . .</p>
}
,但在第一秒你可以看到<p>Loading . . .</p>
在屏幕上,这是else
在上面的条件,然后渲染的其余部分出现了return (<div>CONTENT</div>);
,这是if
在条件。我猜,这意味着渲染方法被触发了两次因为它一直在等待来自数据库的数据。
来自数据库的数据在第一次渲染时不可用,所以,我如何在第一次初始渲染发生之前获取该数据?
您不能对单个组件这样做。您应该遵循容器组件模式,将数据与呈现分离。
let DealersContainer = React.createClass({
getInitialState() {
return {dealersData: []};
},
componentWillMount() {
GetDealersActions.getDealers();
},
render() {
let {dealersData} = this.state;
return (<div>
{dealersData.map((dealer) => {
let props = dealer;
return (<Dealer ...props />); // pass in dealerData as PROPS here
})}
</div>);
}
});
然后更新您的Dealer
组件来接收道具并呈现实际内容。
我的答案与Mathletics的相似,只是更详细。
在这个例子中,我已经将dealerData的状态初始化为null;这是用于确定容器是否从存储区返回数据的检查。
它是冗长的,但是声明性的,并且按照你想要的顺序做你想要的,并且每次都能工作。
const DealerStore = MyDataPersistenceLibrary.createStore({
getInitialState() {
return {
dealerData: null
};
},
getDealers() {
// some action that sets the dealerData to an array
}
});
const DealerInfoContainer = React.createClass({
componentWillMount() {
DealerStoreActions.getDealers();
},
_renderDealerInfo() {
return (
<DealerInfo {...this.state} />
);
},
_renderLoader() {
return (
<p>Loading...</p>
);
},
render() {
const { dealerData } = this.state;
return (
dealerData
? this._renderDealerInfo()
: this._renderLoader()
);
}
});
const DealerInfo = React.createClass({
getDefaultProps() {
return {
dealerData: []
};
},
_renderDealers() {
const { dealerData } = this.props;
return dealerData.map(({ name }, index) => <div key={index}>{name}</div>);
},
_renderNoneFound() {
return (
<p>No results to show!</p>
);
},
render() {
const { dealerData } = this.props;
return (
dealerData.length
? this._renderDealers()
: this._renderNoneFound()
);
}
});
相关文章:
- 将HTML表格导出到excel时,无法将数据加载到excel文件中
- 如何将本地json数据加载到Extjs数据模型中
- FancyTree JS+Backbone.JS-将数据加载到FancyTree时出现问题
- 将数据加载到使用JSON返回的表单字段时出现问题
- 将基本CSV数据加载到D3
- 如何将JSON数据加载到Jqgrid中
- 点击事件时将新的JSON数据加载到Angular中
- 如何使用输入数据加载新的extjs图表
- 读取外部local.txt文件以将数据加载到数组中
- 将数据加载到地图上的更好解决方案
- 将谷歌地理编码(从url)数据加载到javascript变量中
- 按钮在第一次成功的 ajax 数据加载后不起作用
- Jquery 工具提示未随 AJAX 数据加载一起显示
- 将 json 数据加载到 CycleJS 应用程序中
- 将图像数据加载到Angularjs中
- 页面加载前的Angular JS数据加载
- 将数据加载到存储后,Extjs组合框为空
- 将从服务器获取的数据加载到输入文本表单中
- 从 txt 加载数组,将数据加载到 html 中
- 如何将PostgreSQL数据加载到HTML/JS中