[英]How can I asynchronously render a large Component in react-native
我有一個大型組件,該組件在onPress
事件之后呈現,但是我想顯示一些“正在加載...”,直到該組件准備呈現為止。
假設我已經導入了大型組件
import LargeComponent from '../components/LargeComponent'
state={
showComponent: false
}
當我按下按鈕時,它會停留1到2秒鍾,然后渲染該組件,因此,我想異步渲染該組件,並且想要顯示一些負載,直到該組件准備渲染為止
<Button onPress={this.pressHandler} title='show component'/>
{this.state.showComponent ? <LargeComponent/> : null}
pressHandler = () => {
this.setState({
showComponent :true
})
};
React.lazy()
將一個函數作為其參數,該函數必須通過調用import()來加載組件來返回promise。 返回的Promise解析為帶有默認導出的模塊,其中包含React組件。 您也可以為其創建一個HOC並重新使用它。
這是使用React.lazy()
樣子:
import React, { Suspense } from "react";
const LazyLargeComponent = React.lazy(() => {
return new Promise(resolve => setTimeout(resolve, 5 * 1000)).then(
() => import("../components/LargeComponent")
);
});
export default function LargeComponent() {
return (
<div>
<Suspense fallback={<div>loading...</div}>
<LazyLargeComponent />
</Suspense>
</div>
);
}
有關更多信息,請檢查react-api reactlazy
謝謝。
在設置狀態之前,在pressHandler
睡眠2-3秒。
由於您無法發布組件的代碼,因此我不會編寫完整的代碼,但這是一般的想法:
this.state.showComponent
為false和this.state.isLoading
為false this.state.isLoading
設置為true。 這將導致render()
顯示微調器/加載消息 this.state.isLoading
設置為false並將this.state.showComponent
為true 順便說一句,睡眠可以實現如下:
pressHandler = () => {
setTimeout(() => {
this.setState({ isLoading: false, showComponent: true });
}, 3000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.