2016-11-03 41 views
1

我需要從獲取請求中接收一些數據,然後將其作爲道具發送給其他組件。在收到相應狀態之前安裝React組件

但它似乎試圖在接收到我需要的狀態之前呈現其他組件。下面是當前的代碼:

class App extends Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      logList:[], 

     }; 

    } 

    componentWillMount(){ 
     var me=this; 
     var logDirs, currentDirectory; 
     const request = axios.get(baseUrl+"/logs") 
      .then(function(response){ 
       logDirs = response.data.logdirs; 
       currentDirectory = logDirs[me.props.directory]; 
       axios.get(currentDirectory.name) 
        .then(function(response){ 
         me.setState({ 
          logList: response.data.logs 
         }); 

        }); 

     }); 

    } 

    renderLogDirectories(){ 
     if (this.state.logList.length>0){ 
      return (<LogDirectories logs={this.state.logList}/>); 
     } 
    } 

    render(){ 
     if(this.state.logList.length>0) 
      return (
       <div> 
          {this.renderLogDirectories()} 
       </div> 
      ); 

    } 
} 

下面是需要接收道具組件:

class LogList extends Component{ 

    render(){ 
     var me = this; 

     return (
      <ListGroup> 
       <ListGroupItem 
        bsStyle="success">{this.props.directory}</ListGroupItem> 
        {(this.props.logs).map(function (logList, key) { 
         return (
          <Link><ListGroupItem key={key}> 
           {logList} 
          </ListGroupItem></Link>); 
        })} 
      </ListGroup> 
     ); 
    } 
} 

所以,我可以做什麼樣的變化,以得到這個工作?

因爲它是現在,我得到的錯誤是:

Uncaught Invariant Violation: App.render(): A valid React element (or null) must be returned.

Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null (...)

回答

3

你需要返回一個有效的元素,如錯誤說,如果沒有被加載。

render(){ 
    if(this.state.logList.length>0) { 
     return (
      <div> 
       {this.renderLogDirectories()} 
      </div> 
     ); 
    } 
    return (<div>Loading</div>); 

} 
+0

完全忘了這一點。這正是它需要:​​) 謝謝! – theJuls

相關問題