Ошибка отображения имени свойства из извлеченного Axios объекта JSON - PullRequest
0 голосов
/ 07 октября 2019

https://codesandbox.io/s/currying-voice-toq9t - Я пытаюсь сохранить объект json в состояние компонента, а затем отобразить имя в браузере.

  getProfile() {
    axios
      .get(
        "https://cors-anywhere.herokuapp.com/" +
          "https://phantombuster.s3.amazonaws.com....."
      )
      .then(response => {
        this.setState({
          profile: {
            name: response.data.name
          }
        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }

Ответы [ 3 ]

0 голосов
/ 07 октября 2019

Ваши данные ответа - это форма массива, поэтому вам нужно предоставить индекс. Надеюсь, он вам поможет.

getProfile() {
    axios
      .get(
        "https://cors-anywhere.herokuapp.com/" +
          "https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
      )
      .then(response => {
        this.setState({
          profile: {
            name: response.data[0].name
          }
        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }
0 голосов
/ 07 октября 2019

Ваш response.data возвращает массив. Поэтому вам нужно пройти его внутри цикла.

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";

export class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { profile: [] };
  }

  componentDidMount() {
    this.getProfile();
  }

  getProfile() {
    axios
      .get(
        "https://cors-anywhere.herokuapp.com/" +
          "https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
      )
      .then(response => {
        console.log("response: ", response)
        this.setState({
          profile: response.data

        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }

  render() {
    let { name } = this.state.profile;
    const { error } = this.state;

    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Profile</h1>
          {error ? <p>{error.message}</p> : null}
        </header>
        <div className="App-feeds" />
        <div className="panel-list">
        {this.state.profile.map((element) => <p>First Name: {element.name}</p>)}

        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Profile />, rootElement);
0 голосов
/ 07 октября 2019

response.data - это массив, в котором на первой позиции находится информация, которую вы ищете, поэтому setState должен выглядеть следующим образом:

this.setState({
      profile: {
        name: response.data[0].name
      }
    });

или

    const [obj] = response.data;
    this.setState({
      profile: {
        name: obj.name
      }
    });
...