React js извлекает данные из url

#reactjs #fetch

#reactjs #извлечение

Вопрос:

Я пытаюсь заставить свой код отображать пользовательские данные из постоянного URL-адреса, например. «имя» и «имя пользователя». Однако у меня ничего не отображается, когда я пытаюсь просмотреть его в своей локальной среде. Может кто-нибудь помочь мне с кодом, чтобы заставить это работать. Спасибо.

 import React from "react";

export default class FetchRandomUser extends React.Component {
  state = {
    loading: true,
    person: null
  };

  async componentDidMount() {
    const url = "https://jsonplaceholder.typicode.com/users";
    await fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((myJson) => {
      console.log(JSON.stringify(myJson));
      //First check what type of data you are getting here and then try to set your state as below.
      this.setState({person:myJson, loading:false});
    })
    .catch(error => console.error(error)); //If error occurs you will get here
  }
     
  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.person) {
      return <div>didn't get a person</div>;
    }

    return (
      <div>
        <div>{this.state.id}</div>
        <div>{this.state.name}</div>
        <div>{this.state.username}</div>
      </div>
    );
  }
}
  

Ответ №1:

Поскольку API (запрос выборки) возвращает массив объектов, массив человека, а не одного человека. Вам нужно использовать map для перебора одного элемента в вашем массиве.

Кроме того, переименуйте переменную состояния в persons not person . Лучше называть переменную множественным числом, если она представляет массив

 import React from "react";

export default class FetchRandomUser extends React.Component {
  state = {
    loading: true,
    persons: null
  };

  async componentDidMount() {
    const url = "https://jsonplaceholder.typicode.com/users";
    await fetch(url)
      .then(response => {
        return response.json();
      })
      .then(myJson => {
        console.log(JSON.stringify(myJson));
        //First check what type of data you are getting here and then try to set your state as below.
        this.setState({ persons: myJson, loading: false });
      })
      .catch(error => console.error(error)); //If error occurs you will get here
  }

  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.persons) {
      return <div>didn't get a person</div>;
    }

    return (
      <div>
        {this.state.persons.map(person => {
          return (
            <>
              <div>{person.id}</div>
              <div>{person.name}</div>
              <div>{person.username}</div>
            </>
          );
        })}
      </div>
    );
  }
}