开发者问题收集

React Native 中未处理的承诺拒绝错误?

2018-09-04
1383

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

我正在将 react-redux 和 redux-thunk 与 react native 应用程序一起使用。

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);
    });
};

查看以下屏幕截图:

在此处输入图片描述

2个回答

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

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

Axios is a Javascript library used to make http requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. Another feature that it has over .fetch() is that it performs automatic transforms of JSON data.

If you use .fetch() there is a two-step process when handing JSON data. The first is to make the actual request and then the second is to call the .json() method on the response.

Fetch vs. Axios.js for making http requests by Jason Arnold on Medium

James Donnelly
2018-09-04

好的,现在您知道不要像这样编写 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 端点获取数据。

Daniel
2019-05-16