Answer the question
In order to leave comments, you need to log in
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
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?
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]' ? Я хз
render() {
return (
<div>
<h1>
{ this.state.person.map(results => results.name) }
</h1>
</div>
);
}
render() {
return (
<div>
{ this.state.person.map(results => (
<h1> { results.name } </h1>
)
</div>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question