【发布时间】:2019-03-05 22:31:58
【问题描述】:
在我的 react/redux 项目中,我从我的操作中调用一个函数来从 api 获取数据。 Fetch 启动 api 请求...但是 react 无法识别 dispatch()
function getAuthenticatedUser() {
....
return fetch("my.api/path", requestHeaders)
.then(response => handleResponse(response))
.then(response=>{
return response.json()
}).then(responseJson =>{
dispatch(requestSuccess(responseJson.user))
})
....
function requestSuccess(....
....
然后,我将退货包裹如下。现在它没有输出错误,但是 fetch() 没有启动任何 api 请求。 (网络/XHR 中没有请求)
return dispatch => {
return fetch("my.api/path", requestHeaders)
.then(response => handleResponse(response))
.then(response=>{
return response.json()
}).then(responseJson =>{
dispatch(requestSuccess(responseJson.user))
})
}
我错过了什么?
【问题讨论】:
-
在发货前您有没有
console.log()ed,以确认它已经到达那里。此外,请尝试console.log(dispatch)。它是一个函数吗?console.log(requestSuccess(responseJson.user))。它是否返回具有类型/有效负载的对象?在此之后,您需要检查您的减速器。确保调度得到正确处理/捕获。 -
你是在使用 redux-thunk 还是其他一些中间件来处理返回的函数?似乎在第二次尝试中返回的函数没有运行。
-
您在哪里以及如何使用此操作功能?您需要提供minimal reproducible example,因为有很多方法可以调度操作!
-
我要感谢大家。我是 React redux 的初学者,我成功地完成了我的第一次 fetch。我添加了与解决方案相关的答案。