2016-08-18 30 views
0

不知道我在做什麼錯,但我的組件包裹的setTimeout沒有被呈現給DOM:麻煩組件中的setTimeout來渲染

const ContentMain = Component({ 
    getInitialState() { 
     return {rendered: false}; 
    }, 
    componentDidMount() { 
     this.setState({rendered: true}); 
    }, 
    render(){ 
     var company = this.props.company; 

     return (

      <div id="ft-content"> 
       {this.state.rendered && setTimeout(() => <Content company={company}/>,3000)} 
      </div> 
     ) 
    } 
}) 

回答

1

我敢打賭,這是行不通的,因爲render方法需要同時使用其所有輸入,並且不能渲染其他組件,因此有一定的流向React。我建議從render方法超時邏輯的緣故反正分離,做到在componentDidMount這樣的:

const ContentMain = Component({ 
    getInitialState() { 
     return {rendered: false}; 
    }, 
    componentDidMount() { 
     setTimeout(() => { 
      this.setState({rendered: true}); 
     }, 3000); 
    }, 
    render(){ 
     if (!this.state.rendered) { 
      return null; 
     } 

     var company = this.props.company; 

     return (
      <div id="ft-content"> 
       <Content company={company}/> 
      </div> 
     ) 
    } 
}) 

更改狀態觸發渲染方法。

在旁註中 - 即使您的原始方法奏效,每次在初始加載後渲染時,您都會看到組件閃爍3秒。猜測你不會想要的:)

+0

試過了,它不起作用。目錄會在屏幕上顯示。然後過了一段時間(3000年),它做了一些事情。所以它不會延遲渲染,因爲componentDidMount在渲染後運行 – PositiveGuy

+0

初始渲染應該不返回任何內容(因爲this.state.rendered爲false),並且在componentDidMount之後3秒渲染將被設置爲true,這會觸發另一個渲染,新的渲染。如果某些東西不能正常工作,那可能是別的東西了......有什麼錯誤? –

+0

是的,我沒有看到延遲發生,沒有錯誤。 – PositiveGuy