2017-03-06 100 views
1

我試圖編寫簡單的ajax加載程序,我想知道我可以防止props.children呈現在父容器中。問題在於,無論Loader是否要顯示它,以及渲染是否基於ajax數據來填充錯誤,都需要渲染。反應阻止兒童渲染(ajax加載器等待響應)

實施例:https://jsfiddle.net/j8dvsq39/

例2: 這個例子將產生錯誤病程this.state.data.user被AJAX請求之前未定義。

裝載機:用裝載機

import React from 'react' 
export default React.createClass({ 

    getDefaultProps() { 
     return { text: "Loading", loaded: false }; 
    }, 

    render() { 

     if(this.props.loaded == false) 
      return <div>{this.props.text}</div>; 
     else 
      return <div>{this.props.children}</div>; 
    } 
}) 

import React from 'react' 
import Loader from '../helpers/Loader'; 
import {comm} from '../Comm'; 

export default React.createClass({ 

    getInitialState() { 
     return {loaded: false, data: null}; 
    }, 
    componentWillMount(){ 
     comm.get("/xxx/xxx", {json: 1}, (back) => { 
      console.log(back); 
      this.setState({loaded: true, data: back}); 
     }); 
    }, 
    render(){ 
     return <Loader loaded={this.state.loaded}>{this.state.data.user.name}</Loader> 
}); 

回答

0

原因是,首先你定義data=null和AJAX調用之前您使用this.state.data.user.name,它會拋出錯誤:

Cannot read property 'name' of undefined

簡單的解決方案是你需要把檢查數據聯合國直到你沒有得到Ajax響應,選中此:

var Loader = React.createClass({ 
 
    getDefaultProps() { 
 
     return { text: "Loading", loaded: false }; 
 
    }, 
 
    render() { 
 
     if(this.props.loaded == false) 
 
      return <div>{this.props.text}</div>; 
 
     else 
 
      return <div>{this.props.children}</div>; 
 
    } 
 
}); 
 

 
var Hello = React.createClass({ 
 
    getInitialState() { 
 
     return {loaded: false, data: null}; 
 
    }, 
 
    componentWillMount(){ 
 
     setTimeout(()=>{ 
 
      this.setState({loaded: true, data: {user:{name: "login"}}}); 
 
     }, 1000); 
 
    }, 
 

 
    render: function() { 
 
    var user = null; 
 
    return <Loader loaded={this.state.loaded}> 
 
       <div> 
 
       Hello {this.state.data ? this.state.data.user.name : null} 
 
       </div> 
 
      </Loader>; 
 
    } 
 
}); 
 

 
ReactDOM.render(
 
    <Hello name="World" />, 
 
    document.getElementById('container') 
 
);
<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='container'/>

+0

THX的答案。但我知道我可以檢查變量,我只是不想這樣做。我想幹淨的代碼「數據收集後」我知道我可以讓這個類與ifs一起工作,我只是想知道,我可以阻止他們在裝載機。 – rzseattle