2016-08-16 70 views

回答

0

你可以有一個布爾值來切換你的內容的顯示並在AJAX響應中翻轉它。

您可以將此布爾值應用於CSS屬性或整個DIV內容。

下面是可以工作的解決方案。它不會阻止Render被調用,它只會隱藏視圖中的數據相關元素,直到收到呼叫響應。

componentDidMount() { 
    $.ajax({ 
     type: 'GET', 
     url: '/data/', 
     dataType: 'text', 
     success: function(response) { 
      this.setState({show: true, data: response}) 
     }.bind(this) 
    }); 
} 

render() { 
    let {data, show} = this.state; 

    let containerStyle = { 
     display: show ? 'block' : 'none' 
    }; 

    return (
      <div style={containerStyle}> 
       WOW 
       {this.state.pools} 
       <FilterTable rows = {this.state.data} /> 
      </div> 
     ); 
} 
0

如果你不想要這個組件渲染,直到Ajax調用完成後,你應該質疑爲什麼你在所有加載該組件之前Ajax調用完成。 如果您希望Component呈現this.state.pools而不管您是否擁有this.state.data,我會建議您的render方法有條件地呈現FilterTable。

render() { 
     let filterTable; 
     if (this.state.data && this.state.data.length > 0) { // assuming an array 
     filterTable = (
      <FilterTable rows = {this.state.data} /> 
     ); 
     } 
     return (
     WOW 
     {this.state.pools} 
     {filterTable} 
    ); 
} 

但是,如果你想,當你有this.state.data倒不如有這個組件的父執行Ajax調用,只有當必要信息可創建此組件只呈現。一般來說,如果您立即更改componentDidMount中的組件數據,則只需將該信息作爲道具傳遞即可。

+0

對不起,'this.props.data'和'this.props.pool'應該是相同的變量。 –

+0

然後,我肯定會建議只有在擁有所有數據時才創建此組件的實例。 – jhonvolkd

+0

我該怎麼做呢?對不起,我是React的初學者。 –

1

我假設您只想在接收數據時渲染組件。下面的代碼片段呈現了ajax調用成功的組件。 React具有允許我們動態地在DOM中裝入組件的函數。 您將需要導入反應。

import ReactDOM from 'react-dom'; 

componentDidMount() { 
    $.ajax({ 
    type: 'GET', 
    url: '/data/', 
    dataType: 'text', 
    success: function(response) { 
     this.setState({data: response}) 
     ReactDOM.render(<FilterTable rows = {response} />,document.getElementById('filterTableContainer')); 
    }.bind(this) 
}); 
}  
render() { 
let {rows} = this.state.data 
return (
     <div> 
      WOW 
      {this.state.data} 
      <div id="filterTableContainer"></div> 
     </div> 
    ); 
} 
+0

正是我需要的!謝謝! –

2

我寧願選擇一個非常簡單的方法。我將有一個以show set value的名字命名爲false的狀態。並且在回調中成功的ajax返回後,將'show'的值設置爲true。並在渲染中根據'show'的值在返回中安裝jsx代碼。

componentDidMount() { 
    $.ajax({ 
     type: 'GET', 
     url: '/data/', 
     dataType: 'text', 
     success: function(response) { 
      this.setState({data: response, show: true}); 
     }.bind(this) 
    }); 
} 

render() { 
    let {rows} = this.state.data 
    return (
      <div> 
       WOW 
       {this.state.show === true : <div> 
        {this.state.data} 
        <FilterTable rows = {this.state.data} /> 
       </div>: null 
       } 

      </div> 
     ); 
}