【问题标题】:call api response on getting in react js在进入反应js时调用api响应
【发布时间】:2017-12-06 20:07:17
【问题描述】:

我是 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

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

【问题讨论】:

  • 你的调度函数中有两个then
  • 我删除了一个但仍然有错误@Thinker
  • . then(loginResult => console.log(loginResult.token))?也不要使用new Object 使用return {token: json};
  • 怎么样?,我不知道那个@AluanHaddad
  • @PrakashSatani 登录方法返回包含令牌的对象的承诺。所以你需要将一个参数回调传递给then。参数指的是那个对象。

标签: javascript reactjs promise react-redux es6-promise


【解决方案1】:

这是因为您的

getState().mopets_api.token 

未定义。

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

【讨论】:

  • 我检查了console.log(getState().mopets_api,但这显示的是空对象@user1234087
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 2019-10-08
  • 2022-12-14
  • 1970-01-01
相关资源
最近更新 更多