Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - Rendering ReactJS component based on a list of objects

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...