2017-05-03 13 views
0

渲染。 我知道有这集中展示在数据被取出装载其他相关的帖子,但我是有点不同。 我在渲染方法来呈现网格(具有更多的数据),其需要较长的时间的逻辑。在这种情况下,渲染函数将不会显示加载,因为它仍在处理逻辑。 任何帮助,将不胜感激。reactjs问题显示加载而DOM与我现在面临的问题与展示,而DOM是呈现装载更多的逻辑

例如,

class DataGrid extends React.Component { 

    constructor(props, context) { 
    this.state = {isLoading : false} 
    } 

    render(){ 

    //logic to render. 
    .. 
    .. 
    .. 
    //takes long time 
    return(
       <div> 
       <Loader isLoading={this.state.isLoading} /> // This will not work since render is not complete 
       <OtherComponent /> 
       </div> 
    ) 
    } 
} 
+0

说实话,如果它确实需要那么多的时间,你应该移动这种逻辑别处 – stinodes

回答

1

尝试把你的绘制逻辑进行渲染的功能,这样的事情:

class DataGrid extends React.Component { 

    constructor(props, context) { 
     this.state = {isLoading : true} 
    } 

    componentWillMount() { 
     //logic to render 
     //once logic is done: 
     this.setState({ isLoading: false }) 
    } 

    render(){ 

     if (this.state.isLoading) { 
      return <div> 
       <Loader/> 
      </div> 
     } 
     else return (
      <div> 
       <OtherComponent /> 
      </div> 
     ) 
    } 
} 
+0

我通过componentWillReceiveProps接收数据并没有被调用componentWillMount()函数,这是行不通的。我也试过componentWillUpdate(),但没有运气。 –

0

有可能在你的代码的两个问题。

  1. 在你的构造函数,你是不是调用super()方法
  2. 如果你的逻辑需要一定的时间,把一个被调用的渲染和因为JS的异步性质函数内,您return语句将得到执行

class DataGrid extends React.Component { 
 

 
    constructor(props, context) { 
 
    super(props, context); 
 
    this.state = {isLoading : true} 
 
    } 
 
    logicFunc =()=> { 
 
    setTimeout(function() { 
 
     this.setState({isLoading: false})  
 
     
 
    }.bind(this), 5000) 
 
    } 
 
    render(){ 
 

 
    this.logicFunc(); 
 
     
 
    return(
 
       <div> 
 
       <Loader isLoading={this.state.isLoading} /> 
 
       
 
       </div> 
 
    ) 
 
    } 
 
} 
 

 
class Loader extends React.Component { 
 

 
    render() { 
 
    if(this.props.isLoading) { 
 
     return <div>Loading...</div> 
 
    } else { 
 
     return <div>Hello World</div> 
 
    } 
 
    } 
 
    
 
} 
 

 
ReactDOM.render(<DataGrid/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

+0

嗨卡特里,这将作为你有超时为5秒。在情况下,如果我绘制逻辑的时间超过5秒,那么这将失败,因为的setState将启动另一个重新渲染 –

+0

我假设你有一个被触发isrendered状态的基础上的逻辑,否则这将是一个很大更好的想法是让你的逻辑独立于渲染,这样它就不会每次都执行 –