javascript - 进入react js时调用api响应

标签 javascript reactjs promise react-redux es6-promise

我是 redux 和 ReactJs 的初学者。当我尝试调用登录 api 时,我遇到了问题,但没有得到响应。

import { CALL_API } from 'redux-api-middleware';
export function login(toSend) {
    return function(dispatch, getState) {
        dispatch(mopetsLogin(toSend)).then(() =>
        {
            console.log(getState().mopets_api.token.access_token);
            dispatch(mopetsMe(getState().mopets_api.token.access_token));
        });
    }
}

export function mopetsLogin(toSend) {
    console.log('toSend');
    console.log(toSend);
    return {
        [CALL_API]: {
            endpoint: 'http://api.mopets.com/app_dev.php/login',
            method: 'POST',
            /*headers: { 'Content-Type': 'application/json' },*/
            body: JSON.stringify(toSend),
            types: [
                'INITIAL_LOGIN_MOPETS_REQUEST',
                {
                    type: 'INITIAL_LOGIN_MOPETS_SUCCESS',
                    payload: (action, state, res) => {
                        const contentType = res.headers.get('Content-Type');
                        if (contentType && ~contentType.indexOf('json')) {
                            // Just making sure res.json() does not raise an error
                            const contentType = res.headers.get('Content-Type');
                            if (contentType && ~contentType.indexOf('json')) {
                                // Just making sure res.json() does not raise an error
                                return res.json().then((json) => {
                                        var o = new Object();
                                        o["token"] = json;
                                        return o;
                                    }
                                )
                            }
                            ;
                        }
                    }
                },
                'INITIAL_LOGIN_MOPETS_FAILURE'
            ]
        }
    }
}

main.bundle.js:42605 Uncaught (in promise) TypeError: Cannot read property 'access_token' of undefined

显示此类型错误 请查看代码并提供一些信息来解决此问题。

最佳答案

这首先是因为你的

getState().mopets_api.token 

未定义。

也许这只是一个路径问题,请尝试console.log您的资源以检查对象是否正确填充。

关于javascript - 进入react js时调用api响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47673441/

相关文章:

reactjs - 如何乐观地更新 ListView 中的项目

javascript - 1 个节点的 enzyme 模拟

javascript - Ember.js 有很多关系在渲染前未解析

javascript - 应用透视矩阵顺序

javascript - 全局变量是否在文档准备好之前实例化?

javascript - 如何使 <select> 标签项可拖动?

javascript - 如何暂时禁用轮播的 CSS 转换?

javascript - ReactJS/Javascript - 对象中项目的问题渲染组件

javascript - 我应该将单独的功能放入多个 then 回调中吗?

javascript - 将 Array.map() 的结果添加到一个数组中