D
D
depsotr2020-02-20 13:05:34
React
depsotr, 2020-02-20 13:05:34

React API data output?

Добрый день изучаю React такой вопрос , есть два файла файл 1js формирует запрос к API, файл 2js рендерит на страницу, вывел массив данных в консоль , как их же отрендерить на странице  
1.js
export default class Service {

    _apiBase = 'https://swapi.co/api';
    async getResource(url) {
      const res = await fetch(`${this._apiBase}${url}`);
  
      return await res.json();
    }
  
  async getAllPeople() {
    const res = await this.getResource(`/people/`);
    return res.results
    // .map(results => results.name);
    }
  
  }

2.js
import React, { Component } from 'react';
import Service from './Services';


export default class App extends Component {

    service = new Service();
  

 state = {
     person: null
 }

    componentDidMount() {
        this.service.getAllPeople()
        .then((res) => {
            this.setState({
                person: res,
            })
            console.log(res.map(results => (
                results.name
            )));
        })

        
    }



   

    render() {


        return (
            <div>
                <h1>
                  
                </h1>
            </div>
        );
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
McBernar, 2020-02-20
@McBernar

Well, post something okay. Could you attach a screenshot of the code.
You have a render function in your component that is responsible for rendering elements. You have a person array in the state. Do a map of this array in render and return the desired elements. Where is your problem?

E
Egor Zhivagin, 2020-02-20
@Krasnodar_etc

I think you don't really understand what you're doing. There is a whole article in the react docs about outputting lists - check
out You are now taking and "saying" React: draw me an array inside a block .
This is conditionally similar to this code:

var array = [1,2,3];
someElement.innerHTML = array; // Вот что тут выведется? Object object? Строка '[1,2,3]' ? Я хз

You need to do your loop directly in the template
render() {
        return (
            <div>
                <h1>
                 { this.state.person.map(results => results.name) }
                </h1>
            </div>
        );
    }

But I, unfortunately, cannot guess how you want to display this data. Do you want each field to be in an h1 tag? You are welcome:
render() {
        return (
            <div>
                 { this.state.person.map(results => (
                      <h1> { results.name } </h1>
                  )
            </div>
        );
    }

I hope the logic is clear. Please read the react documentation for more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question