【问题标题】:TypeError from axios get on a json endpoint来自 axios 的 TypeError 在 json 端点上
【发布时间】:2018-04-12 00:42:01
【问题描述】:

我从响应中得到了我需要的数据,但是我得到一个 TypeError 并且我不明白为什么?我需要做什么来解决这个问题?

  componentDidMount() {
    const getData = axios.get("https://web-code-test-xxx-games-prd.appspot.com/cards.json")
      .then(function(response) {
        const easyResponse = response.data.levels[0]['difficulty']
        const easyCards = response.data.levels[0]['cards']
        this.setState({ easy: easyResponse})
        this.setState({easyCards: easyCards})

       })
      .catch(function(error) {
        console.log(error);
      });

}

【问题讨论】:

  • 错误是什么?
  • TypeError{},我四处寻找更详细的解释,但没有运气。是因为它获取一个 json 吗?
  • 这是响应对象 {data: Object, status: 200, statusText: "", headers: Object, config: Object...} data: Object levels: Array[2] 0: Object 1:对象状态:200 statusText:“”标头:对象配置:对象请求:XMLHttpRequest
  • TypeError 来自我设置状态的方式

标签: javascript reactjs axios


【解决方案1】:

TypeError 不在 get 请求中,它来自返回的 Promise 对象。 Axios 是一个异步操作,并且 Axios 内部的“this”丢失/不同,因此 this.setState 中的“this”没有被正确读取。通过切换到箭头函数,“this”不再是 axios 对象,而是上下文对象,即反应组件。这里是another answer

【讨论】:

    猜你喜欢
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2021-03-01
    • 2021-12-18
    • 2021-01-20
    相关资源
    最近更新 更多