【发布时间】: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