從我的理解:
您正在試圖安裝一個MainApp
組件,顯示了.loader-container
div
默認情況下,同時它檢索一些data
。
當所說的data
回來:您希望您的組件從視圖中刪除.loader-container
併爲您的SomeComponent
提供數據。
您目前的實施缺少一些重要的邏輯。特別是,邏輯會告訴您的預加載器何時關閉。這種邏輯需要使用promises
。
有關如何執行此類實現的示例,請參見下文。
我已經包括一對夫婦的流血戰略,如try
,catch
,async
和await
。我強烈建議閱讀this article以進一步瞭解它們。一旦你瞭解它們,它們就非常簡單而有用,特別是與承諾和回調相比。
class MainApp extends React.Component {
// Constructor.
constructor(props) {
super(props)
// Initial State.
this.state = {
data: false,
loading: true
}
}
// Will Mount.
componentWillMount() {
// Fetch whatever data you might need here.
this.fetchData()
}
// Render.
render() {
// Loading?
if (this.state.loading) {
// Return Loader Container.
return (
<div id="loader-container" />
)
}
// Data?
if (!this.state.data) {
return (
<div>Eror: !Data.</div>
)
}
// You are good to go.
return (
<SomeComponent data={this.state.data}/>
)
}
// Typical Function To Retrieve All Applicable Data.
fetchData = async() => {
try {
// Fetch data.
const data = await fetchData() // INSERT A PROMISE TO FETCH YOUR DATA HERE.
// Update state to include data/disable loader.
this.setState({
data,
loading: false
})
} catch (error) {
// Handle any errors that might occur.
console.log(error)
}
}
}
嘿@ kakamg0,爲何你指的是一個http請求?在我的情況下,SomeComponent是一個常量組件。 –
對不起,我想當你說裝載完成之前預裝載程序已經消失的時候,你正在談論一個請求。但我看到你已經找到了解決方案。 – kakamg0