【问题标题】:fetch api call data is not definedfetch api 调用数据未定义
【发布时间】:2018-12-10 00:56:10
【问题描述】:

大家好,我有一个响应应用程序发出 fetch api 获取请求。当我在将响应转换为 json 后控制台记录响应时,它工作正常,但是当我尝试使用数据设置状态时,它说它没有定义。我错过了什么?

  componentDidMount() {
    fetch('/api/logs')
      .then(res => res.json())
      // .then(data => console.log(data))
      .then(this.setState({ Log: data }))
      .catch(error => console.log(error))
  }

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    第二个链需要一个回调函数,setState 不是。

     componentDidMount() {
        fetch('/api/logs')
          .then(res => res.json())
          .then((data) => this.setState({ Log: data })) // <---- wrap setState inside callback
          .catch(error => console.log(error))
      }
    

    【讨论】:

    • 你很善良
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2022-01-18
    • 2020-01-19
    • 2018-07-08
    相关资源
    最近更新 更多