反应防止儿童渲染(ajax装载机等待响应)

时间:2017-03-06 07:29:23

标签: ajax reactjs

我试着编写简单的ajax加载器,我想知道我可以阻止props.children在父容器中渲染。问题是孩子们想要渲染,无论Loader是否想要显示它,以及渲染是否基于ajax数据来缓解错误。

示例:https://jsfiddle.net/j8dvsq39/

例2: 此示例将产生错误,在ajax请求之前未定义this.state.data.user。

装载机:

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>;
    }
})

使用Loader的类

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>
});

1 个答案:

答案 0 :(得分:0)

原因是,最初您定义了data=null,在使用this.state.data.user.name的ajax调用之前,它会抛出错误:

  

无法读取未定义的属性“名称”

简单的解决方案是你需要检查数据,直到你没有得到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'/>