反应本机中未处理的承诺拒绝错误?

时间:2018-09-04 12:59:24

标签: javascript reactjs react-native axios

我正在使用axios从API端点获取数据。我收到错误->可能未处理的承诺拒绝类型错误:undefined不是一个函数(正在评估res.json())

我正在将React-redux和redux-thunk与React本机应用程序一起使用。

venueAction.js:

import { FETCH_VENUES } from './types';
import axios from 'axios';

export const fetchVenues = () => dispatch => {
    axios.get(`my_api_link`)
    .then( res => res.json())
    .then( venues => 
        dispatch({
            type: FETCH_VENUES,
            payload: venues
        })
    )
    .catch( error => {
        console.log(error);
    });
};

检查以下屏幕截图:

enter image description here

2 个答案:

答案 0 :(得分:5)

需要在响应上调用json()Fetch API的一部分。相反,Axios实现了XMLHttpRequest,这意味着您不需要这样做。

axios.get(`my_api_link`)
  .then(venues => {
    ...
  });

  

Axios是一个Javascript库,用于从浏览器发出来自node.js的HTTP请求或来自浏览器的XMLHttpRequests,它支持JS ES6固有的Promise API。 .fetch()具有的另一个功能是,它可以执行JSON数据的自动转换。

     

如果使用.fetch(),则处理JSON数据时将分两步进行。第一种是发出实际的请求,然后第二种是在响应上调用.json()方法。

     

— Jason Arnold在媒体上的Fetch vs. Axios.js for making http requests

答案 1 :(得分:0)

好的,现在您知道不要这样编写axios代码了:

export const fetchVenues = () => dispatch => {
    axios.get(`my_api_link`)
    .then( res => res.json())
    .then( venues => 
        dispatch({
            type: FETCH_VENUES,
            payload: venues
        })
    )
    .catch( error => {
        console.log(error);
    });
}; 

现在呢?尝试使用ES8 async / await语法,如下所示:

export const fetchVenues = () => async dispatch => {
      try {
        const url = 'http://api.funwithredux.com/';
        let { data } = await axios.get(url);
        dispatch({ type: FETCH_VENUES, payload: data });
        console.log(data);
      } catch (e) {
        console.log(e);
      }
    };

如您所见,您可以使用try / catch语句捕获任何错误,我肯定会添加一个控制台日志,以确保您也从API端点获取了数据。