来自axios的TypeError获取json端点

时间:2018-04-12 00:42:01

标签: javascript reactjs axios

我从响应中获取了我需要的数据,但是我得到了一个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);
      });

}

1 个答案:

答案 0 :(得分:0)

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