Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following component:

articles_list.jsx

import React from 'react';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  render() {

    var teste = () => {
      if (this.state.articles === null) {
        return(<div>No articles</div>)
      } else {
          {this.state.articles.forEach( function(element, index) {
            console.log(element);
            return <div key={index}>{element.title}</div>;
          })}
      }
    }

    return(
      <div className="articles_list">
        <div className="articles_list_title">
          ARTICLES
        </div>
        <div>{teste()}</div>
      </div>
    );
  }
}

Although the JSON request is working fine and returning an array with five JSON objects, they just don't render!

I am new to ReactJS and read (and watched) lots of tutorials, but it seems I am missing something.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

You may try something like this.

import _ from 'lodash';
renderArticles() {
  return _.map(this.state.articles, article => {
    return (
      <li className="list-group-item" key={article.id}>
          {article.title}
      </li>
    );
  });
}


  render() {
    return (
      <div>
        <h3>Articles</h3>
        <ul className="list-group">
          {this.renderArticles()}
        </ul>
      </div>
    );
  }

Map over the list and render it one by one. Here I am using lodash map helper to get this done. Hope this helps. Happy coding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...