Problems compiling a component in react.js

0

I'm trying to build a component that receives parameters. This component is called when, you press a news item on a main page. The only parameter that happened manually is the property slug .

The component I have defined it this way:

import React, { Component } from 'react';
import axios from 'axios';


class Articulo extends Component {

  constructor(props) {
    super(props);
    this.state = {
      url : 'http://aldeasinfantiles-wp.lin3sdev.com/wp-json/wp/v2/posts?slug=' + this.props.match.params.slug
    }
  }

  state = {
    articles: [],
  };

  componentDidMount() {
    axios.get(this.state.url).then(res => {
      this.setState({ articles: res.data});
    });

  };

  render() {

      console.log(this.state.articles)
      return (<div className='articles-wrapper'></div>)
  }

}

export default Articulo;

As it is the code does not throw me any error, but I need to go through the array articles to be able to write it in html. I tried two options and none of them worked.

Option 1:

render() {
      return (<div className='articles-wrapper'>
         {this.state.articles.map( articulo => <h1>{articulo.title.rendered}</h1>)
        </div>)
  }

Option 2:

Access the data of the array directly:

  render() {
        return (<div className='articles-wrapper'><h1>{articulo.title.rendered</div>)
    }

In both cases, it sends me the following error:

Launches the error:

  

TypeError: this.state.articles is undefined

This error I understand that it is because the first time it renders the component, articles is empty, hence if I do console.log(this.state.articles) it returns undefined . It is not until you access componentDidMount() and assign a value to the array articles .

I tried to test with a conditional so that at the time of rendering it checks if articles is empty or not:

render() {
      if (this.state.articles.length > 0) {
        return (<div>El array está vacío</div>)
      } else {
        return (<div className='articles-wrapper'><h1>{this.state.articles[0].title.rendered}</h1></div>)
      }
    }

But I still have the same problem.

    
asked by JetLagFox 11.07.2018 в 23:45
source

2 answers

2

The error is:

   state = {
     articles: [],
   };

You need to declare articles inside the constructor next to 'url' and not outside it:

  constructor(props) {
    super(props);
    this.state = {
       url : 'http://aldeasinfantiles-wp.lin3sdev.com/wp-json/wp/v2/posts?slug=' + this.props.match.params.slug,
       articles: []
     };
   }
    
answered by 19.07.2018 в 19:30
1

Finally I have solved it by modifying the way it traversed the array:

this.state.articles.map(articulo => {
     return (
        <article className='article-wrapper' key={articulo.id}>
           //contenido
        </article>  
     )
  })
    
answered by 12.07.2018 в 22:51