【发布时间】:2017-05-03 05:01:58
【问题描述】:
我是 React、Redux 和 JS 的新手。我想知道如何在另一个完成后调度和采取行动 - 以正确的方式承诺。我的代码确实有效,但它不断抛出错误:
readingActions.js?14b9:56 Uncaught (in promise) TypeError: dispatch(...).then is not a function(…)
这是我的设置。
-
这是我的动作创建者,我想要链接动作以及发生警告的位置。
export function createReading(reading) { return function (dispatch) { dispatch({type: CREATE_READING}); return request( `${API_URL}new`, {method: 'POST', body:JSON.stringify(reading)}, (json) => {( dispatch({type: CREATE_READING_SUCCESS, res: json}).then(dispatch(Notifications.success(showSuccess(json.book.title)))))}, (json) => { dispatch({type: CREATE_READING_ERROR400, res: json}).then(dispatch(Notifications.error(showError(json.error)))) }, (res) => { dispatch({type: CREATE_READING_ERROR500, res: res}) }, (ex) => { dispatch({type: CREATE_READING_FAILURE, error: ex}) }, ) } }
如您所见,问题出在 .then 中,因为我不知道如何正确触发操作。
-
您还可以看到请求是我的辅助函数,看起来像这样(这里我附加令牌,返回不同的响应):
export function request(url, options, success, error400, error, failure) { let headers = new Headers(); headers.append("Content-Type", "application/json") headers.append("Accept", "application/json") options["headers"] = headers; if (localStorage.jwtToken) { let token = localStorage.jwtToken; headers.append('Authorization', 'JWT '+token); } return fetch(url, options) .then(res => { if (res.status >= 200 && res.status < 300) { res.json().then(json => { return success(json) }) } else if (res.status === 400) { res.json().then(json => { return error400(json) }) } else { return error(res) } }).catch((ex) => { return failure(ex) }) }
问题是如何正确执行 .then 以及正确的方法是什么?
【问题讨论】:
标签: javascript reactjs redux redux-thunk