React Fetch API数据-对象未定义

时间:2018-08-24 13:48:53

标签: node.js reactjs

我正在尝试从Shipstation中提取JSON数据。我现在要做的就是将数据存储在一个名为Orders的状态对象中,并将货件ID呈现到页面上。我收到以下错误:

第25行:no-undef未定义“订单”

import React, { Component } from "react";
class Orders extends Component {
  constructor(props) {
    super(props);
    this.state = {
      orders: []
    };
  }

  componentDidMount() {
    let key = "[MY KEY GOES HERE]";
    let secret = "[MY SECRET GOES HERE]";
const encodedString = new Buffer(key + ":" + secret).toString("base64");

fetch("https://ssapi.shipstation.com/orders/", {
  headers: {
    Authorization: "Basic " + encodedString
  }
})
  .then(res => res.json())
  .then(data => {
    this.setState({ orders: data });
    console.log(orders);
      })
      .catch(err => console.log(err));
  }

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

const orderItems = orders.map(order => (
  <div key={order.id} className="card card-body mb-2">
    <div className="row">
      <div className="col-md-6">
        <p>{order.orderId}</p>
      </div>
    </div>
  </div>
));
return (
  <div ref="myRef">
    <hr />
    <h3 className="mb-4">Recent Shipments</h3>
    {orderItems}
  </div>
);
  }
}

export default Orders;

1 个答案:

答案 0 :(得分:1)

那看起来像是ESLint错误,只是说你做不到

console.log(orders);

因为此时您实际上尚未在任何位置定义变量。

您可以将代码更改为:

const orders = data;
this.setState({ orders });
console.log(orders)

一切正常。