2017-10-20 61 views
0

我試圖實現反應的預加載器,反應,並在負荷事件

我嘗試以下

class MainApp extends React.Component { 

    componentDidMount() { 
    this.preloader.style.display = 'none'; 
    } 

    render() { 
    return (
     <div id="loader-container" ref={(c) => { this.preloader = c; }} /> 
     <SomeComponent /> 
    ); 
    } 
} 

然而,似乎預加載器加載之前即消失長做完了。

如何將預加載程序的刪除綁定到加載事件?

回答

0

我認爲問題是當你的父組件(MainApp)被掛載並且請求可能尚未完成時,你隱藏了加載器容器。

您可以傳遞到子組件一種功能,當加載完成這樣的呼籲:

class MainApp extends React.Component { 
    constructor (props) { 
     super(props); 
     this.hideLoader = this.hideLoader.bind(this); 
    } 

    hideLoader() { 
     this.preloader.style.display = 'none'; 
    } 

    render() { 
     return (
      <div id="loader-container" ref={(c) => { this.preloader = c; }} /> 
      <SomeComponent onLoaded={this.hideLoader} /> 
     ); 
    } 
} 

而且在SomeComponent你應該叫this.props.onLoaded()當請求完成。事情是這樣的:

class SomeComponent extends React.Component { 
    componentWillMount() { 
     fetch(url) 
     .then(response => { 
      this.setState(...); 
      this.props.onLoaded(); 
     }); 
    } 
} 
+0

嘿@ kakamg0,爲何你指的是一個http請求?在我的情況下,SomeComponent是一個常量組件。 –

+0

對不起,我想當你說裝載完成之前預裝載程序已經消失的時候,你正在談論一個請求。但我看到你已經找到了解決方案。 – kakamg0

0

好了,所以我用

window.addEventListener('load', this.handleLoad); 

componentDidMount

handleLoad() { 
    $('#loader-container').hide(); // $ is available here 
    } 

似乎做的工作

感謝

0

從我的理解:

您正在試圖安裝一個MainApp組件,顯示了.loader-containerdiv默認情況下,同時它檢索一些data

當所說的data回來:您希望您的組件從視圖中刪除.loader-container併爲您的SomeComponent提供數據。


您目前的實施缺少一些重要的邏輯。特別是,邏輯會告訴您的預加載器何時關閉。這種邏輯需要使用promises

有關如何執行此類實現的示例,請參見下文。

我已經包括一對夫婦的流血戰略,如try,catch,asyncawait。我強烈建議閱讀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) 
    } 
    } 
}