无法从 axios 获取的 json 对象中显示名称 属性

Trouble display name property from axios fetched json object

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 }));
  }

response.data是一个数组,第一个位置是你要查找的信息,所以setState应该是这样的:

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

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

你的Response数据是数组形式所以,你需要给Index.I希望对你有帮助

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 }));
  }

你的 response.data returns 和 array.so 你需要在循环中遍历它。

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);