Retrieve backend data in ComponentDidMount or in ComponentWillMount

3

I have the following component:

import React, { Component } from 'react'
import data from '../data/dummyDataEx.json'

export default class Resumen extends Component {

  constructor (...args) {
    super(...args)
    this.state = {
      results: []
    }
  }

  componentDidMount() {
    this.setState({ results: data })
  }

  render() {
    const { datos } = this.state.results
    return (
      <div>
        <br/>
        <p>Título: {datos.titulo}</p>
        <p>Actualización: {datos.actualizacion}</p>
        <p>Estado: {datos.estado}</p>
      </div>
    )
  }
}

and the dummyDataEx.json

{
  "datos": {
    "titulo": "Esto es el título",
    "actualizacion": "22/10/2016 19:10:42",
    "estado": "Cerrado"
  }
}

Execution of this component gives an error:

  

Uncaught TypeError: Can not read property 'title' of undefined

    
asked by Sergio Martinez 23.10.2016 в 12:22
source

1 answer

2

The problem is that you are using componentDidMount , but you should use componentWillMount . These methods are invoked in a specific order, known as Life Cycle or Life Cycle.

Events occur in the following order:

As you can see, componentDidMount is executed after render and therefore the state that you set there, is not yet defined at the moment that render is invoked.

Here is an example that I have refactored a bit to work on the StackSnippet, but it is equivalent to your previous example.

Salu2

var data = {
  "datos": {
    "titulo": "Esto es el título",
    "actualizacion": "22/10/2016 19:10:42",
    "estado": "Cerrado"
  }
}

var Resumen = React.createClass({
  getInitialState: function() {
    return {
      results: []
    };
  },
  componentWillMount: function() {
    this.setState({
      results: data
    })
  },
  render: function() {
    const { datos } = this.state.results
    return (
      <div>
            <br/>
            <p>Título: {datos.titulo}</p> 
            <p>Actualización: {datos.actualizacion}</p>
            <p>Estado: {datos.estado}</p>
          </div>
    )
  }
});

ReactDOM.render(<Resumen/>, document.querySelector('.main'))
<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 class="main"></div>
    
answered by 23.10.2016 / 17:50
source