TypeError: records.map is not a function - First React project, stuck on this error with API

TypeError: records.map is not a function - First React project, stuck on this error with API

我一直在尝试从当地政府获取数据API

https://data.qld.gov.au/api/action/datastore_search?offset=370&resource_id=2bbef99e-9974-49b9-a316-57402b00609c&q=Mooloolaba

我已经设法将示例 API 数据加载到我的项目中,但是当我去使用这个 API 我 运行 出错了,我认为这是因为我没有我不确定 set.state 部分是否正确,但我不确定,因为我以前从未使用过 APIs,而我使用的这个部分的结构与示例不同。

另外我只想得到最新的结果,这个API每半小时更新一次。如果我做错了什么是黑白分明的,请在解决我的问题之前指出正确的方向我想了解我哪里出了问题:)

// Waves //

const WAPI = 'https://data.qld.gov.au/api/action/datastore_search?offset=370&resource_id=2bbef99e-9974-49b9-a316-57402b00609c&q=Mooloolaba';

class WApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      records: [],
    };
  }

  componentWillMount() {
    fetch(WAPI)
      .then(response => response.json())
      .then(data => this.setState({ records: data.records }));
  }

  render() {
    const { records } = this.state;

    return (
      <ul>
        {records.map(record =>
          <li>
          {record.Hsig} m
            {record.Direction} direction
          </li>
        )}
      </ul>
    );
  }

}

您的第一个问题是(如您所想)使用了错误的对象 属性。应该是data.result.records。现在,为什么数据是空的?我认为您使用了错误的 API 端点。我为 hot 数据找到了这个:https://data.qld.gov.au/dataset/coastal-data-system-near-real-time-wave-data/resource/2bbef99e-9974-49b9-a316-57402b00609c

这是工作代码。顺便说一下,使用 componentDidMount 而不是 componentWillMount 因为它在未来会被弃用。

const WAPI = 'https://data.qld.gov.au/api/action/datastore_search?resource_id=2bbef99e-9974-49b9-a316-57402b00609c&q=Mooloolaba';

class WApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      records: [],
    };
  }

  componentDidMount() {
    fetch(WAPI)
      .then(response => response.json())
      .then(data => this.setState({ records: data.result.records }));
  }

  renderRecords = () => this.state.records.map(record =>
      <li key={record._id}>
        {record.Hsig} m
        {record.Direction} direction
      </li>
  );

  render() {
    const { records } = this.state;

    return (
      <ul>
        {!records.length ? <p>Loading...</p> : this.renderRecords() }
      </ul>
    );
  }

}

ReactDOM.render(<WApp />, 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>