Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
React expose component function and getting data with ComponentDidMount

This is regarding a question that I have just asked here : React expose component function

So when using componentDidMount on the 2 components where the functions are exposed, it looks like the componentDidMount for the data function takes some time to load, and then this causes returning an empty array. I am pretty new to react so I am not sure if this is the right way to use them.

class Data extends React.Component {
    constructor() {
        super();
        this.state = {
            names: []
        }
    }
    componentDidMount() {
        $.get('data.json', function (result) {
            this.setState({
                names: result.names
            });
        }.bind(this));
    }

    getNames(){
        return this.state.names;
    }

    render(){
        return (<div></div>);
    }

}


class Layout extends React.Component {
    constructor(){
        super();
        this.state = {
            test: []
        };

    }

    componentDidMount() {
        this.state.test = this.refs.hello.getNames();
        console.log(this.refs.hello.getNames());
    }

    something(){
        console.log(this.state.test);
    }


    render(){
        return(
            <div>
                <Data ref='hello' />
                {this.something()}
            </div>
        )
    }
}

const app = document.getElementById('app');

ReactDOM.render(<Layout />,  app);
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You have done a mistake of assigning value to a state in the layout component like this.state.test = this.refs.hello.getNames();, where you should be using setState(); Also it better to retrieve the data in the Layout component and if you want to use the data in Data component too then you can pass it as a prop to the same like

class Data extends React.Component {
    constructor() {
        super();
    }
    render(){
        console.log(this.props.names)
        return (<div></div>);
    }

}


class Layout extends React.Component {
    constructor(){
        super();
        this.state = {
            test: []
        };

    }

    componentDidMount() {
        $.get('data.json', function (result) {
            this.setState({
                test: result.names
            });
        }.bind(this));

    }

    something(){
        console.log(this.state.test);
    }


    render(){
        return(
            <div>
                <Data ref='hello' names={this.state.test}/>
                {this.something()}
            </div>
        )
    }
}

const app = document.getElementById('app');

ReactDOM.render(<Layout />,  app);
over 4 years ago · Santiago Trujillo Denunciar

0

The problem here is that you are fetching in componentDidMount, you should be fetching in componentWillMount, that way you have the data before the component is rendered

Per the docs:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), (therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.)

All you need to do is change componentDidMount to componentWillMount

https://facebook.github.io/react/docs/react-component.html#componentwillmount

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda