使用React获取外部API数据:this.state为空

时间:2018-08-12 08:45:31

标签: reactjs

我一直不走运地尝试解决从API提取数据的问题。我在想这可能是因为JSON结构阻止了setState成功完成。

控制台日志显示返回的空数组。

myresults.jsx

import React, {Component} from 'react';
import fetch from 'isomorphic-fetch';

const URL = 'http://localhost:8080/data/races/all';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      results: [],
    };
  }

  componentDidMount() {
    fetch(URL)
      .then(results => results.json())
      .then(data => this.setState({ results: data[0]}));
  }

  render() {
    console.log(this.state.results);
    return (
      <div>
        {this.state.results}
      </div>
    );
  }
}

export default App;

localhost的JSON:8080 / data / races / all:

[
  {
    "url": "www",
    "year": 2018,
    "Name": "Rabbit",
    "Id": 1
  },
  {
    "url": "www",
    "year": 2018,
    "Name": "Cat",
    "Id": 2
  },
  {
    "url": "www",
    "year": 2018,
    "Name": "Dog",
    "Id": 3
  }
]

1 个答案:

答案 0 :(得分:0)

如注释中所述,使用返回的所有数据设置您的状态,而不仅仅是设置一项。获取数据后,您需要进行映射以呈现DOM。请勿使用this.state.results之类的整个数据。

import React, {Component} from 'react';
import fetch from 'isomorphic-fetch';

const URL = 'http://localhost:8080/data/races/all';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      results: [],
    };
  }

  componentDidMount() {
    fetch(URL)
      .then(results => results.json())
      .then(data => this.setState({ results: data }));
  }

  render() {
        return (
      <div>{
        this.state.results.map( result => (
          <ul>
            <li>{result.url}</li>
            <li>{result.year}</li>
            <li>{result.Name}</li>
            <li>{result.Id}</li>
          </ul>
        ) )
      }
      </div> );
  }
}

export default App;

以下是模仿您的情况的示例:

const data = [
  {
    url: "www",
    year: 2018,
    Name: "Rabbit",
    Id: 1,
  },
  {
    url: "www",
    year: 2018,
    Name: "Cat",
    Id: 2,
  },
  {
    url: "www",
    year: 2018,
    Name: "Dog",
    Id: 3,
  },
];

class App extends React.Component {
  state = {
    results: [],
  }


  componentDidMount() {
    this.getData().then( results => this.setState( {
      results,
    } ) );
  }

  getData() {
    return new Promise( resolve => resolve( data ) );
  }

  render() {
    return (
      <div>{
        this.state.results.map( result => (
          <ul>
            <li>{result.url}</li>
            <li>{result.year}</li>
            <li>{result.Name}</li>
            <li>{result.Id}</li>
          </ul>
        ) )
      }
      </div> );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>