[英]How can I prevent Angular from rendering and displaying a page before ng-if evaluation?
[英]How can I prevent a component from rendering before data is loaded?
我正在等待來自名為GetDealersStore
的商店的道具,我獲取數據的方式是我正在執行的操作:
componentWillMount () { GetDealersActions.getDealers(); }
我已經測試了app並且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>
<p>Loading . . .</p>
<p>Loading . . .</p>
在屏幕上是上面條件中的else
,然后渲染的其余部分出現return (<div>CONTENT</div>);
這是條件中的if
。 所以,我想,這意味着render方法已經被觸發兩次,因為它一直在等待來自數據庫的數據。
數據庫中的數據在第一次渲染時不可用,因此,如何在第一次初始渲染發生之前獲取該數據?
您不能使用單個組件執行此操作。 您應該遵循容器組件模式以將數據與呈現分開。
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()
);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.