繁体   English   中英

API响应显示在console.log中,但未显示在react页面上

[英]API response showing in console.log but not on react page

我试图显示APi响应的一部分,但是当我尝试解析它时,它总是给我未定义的信息。

我尝试做API响应的2部分,但没有用。

class App extends Component {
  constructor() {
    super();
    this.state = {
      head: 0,
      data: [],
      firstName: "Brad",
      lastName: "Marchand",
      err: null
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:3001/api/player", {
        params: {
          firstName: this.state.firstName,
          lastName: this.state.lastName
        }
      })
      .then(response => {
        this.setState({
          data: response.data
        });
        console.log(this.state.data);
      })
      .catch(err => {
        //this.err = err;
      });
  }

  render() {
    return (
      <>
        <p>{this.state.data.players[0].player.firstName}</p>
        <p>Hello</p>
      </>
    );
  }
}

后端

 request(options, (err, response, body) => {
    if (err) {
      signale.error(err);
    }
    var data = JSON.parse(body);
    //var data = JSON.stringify(data.players);
    //var data = JSON.parse(data);

    signale.success(data);
    res.send(data);
  });
{ lastUpdatedOn: '2019-08-15T15:20:13.791Z',
[0]   players: [ { player: [Object], teamAsOfDate: [Object] } ],
[0]   references: { teamReferences: [ [Object] ], venueReferences: [ [Object] ] } }

另一个预期的回应另一个回应

尝试只输出我想要的响应,但始终无法通过this.state.data获得定义

因此,这里的问题是,您正在componentDidMount中进行API调用,并且API的响应肯定会在初始渲染之后出现,并且在初始渲染中, this.state.data.players[0].player.firstName是未定义的它破坏了您的代码。 在访问该值之前,请添加条件检查。 如果一个data状态也将其初始化为一个对象

class App extends Component {
  constructor() {
    super();
    this.state = {
      head: 0,
      data: {},
      firstName: "Brad",
      lastName: "Marchand",
      err: null
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:3001/api/player", {
        params: {
          firstName: this.state.firstName,
          lastName: this.state.lastName
        }
      })
      .then(response => {
        this.setState({
          data: response.data
        });
        console.log(this.state.data);
      })
      .catch(err => {
        //this.err = err;
      });
  }

  render() {
    return (
      <>
        <p>{this.state.data.players && this.state.data.players[0].player.firstName}</p>
        <p>Hello</p>
      </>
    );
  }
}

React setState()是异步工作的,这意味着在状态中设置值会稍有延迟。 您可以将回调传递给setState(),状态更新后将调用该回调。

 this.setState({
     data: response.data
 }, () => { console.log(this.state.data); });

干杯,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM