Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
react prevent children render ( ajax loader waiting for response )

Im trying to write simple ajax loader and I wondering that i can prevent props.children render in parent container. The problem is that children want to render, no matter that Loader want to show it or not, and if render is based on ajax data that cousing errors.

Example: https://jsfiddle.net/j8dvsq39/

Example2: This example will produce error couse this.state.data.user is undefined before ajax request.

Loader:

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

Class using 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>
});
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Reason is, initially you defined data=null and before the ajax call you are using this.state.data.user.name, it will throw the error:

Cannot read property 'name' of undefined

Simple solution is you need to put the check on data until you didn't get the ajax response, Check this:

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'/>

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda