【问题标题】:Unhandled promise rejection error in react native?反应本机中未处理的承诺拒绝错误?
【发布时间】:2019-02-09 12:37:07
【问题描述】:

我正在使用 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);
    });
};

查看下面的截图:

【问题讨论】:

    标签: javascript reactjs react-native axios


    【解决方案1】:

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

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

    Axios 是一个 Javascript 库,用于从浏览器发出来自 node.js 或 XMLHttpRequests 的 http 请求,它支持 JS ES6 原生的 Promise API。它比 .fetch() 具有的另一个特性是它执行 JSON 数据的自动转换。

    如果您使用 .fetch(),则在处理 JSON 数据时有两个步骤。第一个是发出实际请求,然后第二个是在响应上调用 .json() 方法。

    Fetch vs. Axios.js for making http requests 来自 Medium 上的 Jason Arnold

    【讨论】:

    • 所以如果我删除 .then( res => res.json()) 它工作正常 :)
    【解决方案2】:

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

    【讨论】:

    • 他的抓取技术没有问题。除了个人喜好之外,不需要异步/等待。他只要求删除.then( res => res.json())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多