【问题标题】:Fetch and dispatch in a redux action function在 redux 操作函数中获取和调度
【发布时间】: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。我添加了与解决方案相关的答案。

标签: reactjs redux jsx


【解决方案1】:

我找到了解决方案。首先我要感谢 3 cmets 关于这个问题。

我首先安装了 redux-thunk。我在商店中添加了一个中间件:

import thunk from "redux-thunk";
...
export const store = createStore(
    rootReducer,
    applyMiddleware(thunk)
);

然后,我在组件中导入了 store 并调度了我的操作函数。 (之前我是直接调用的)

constructor(props) {
    ....
    store.dispatch(userActions.getAuthenticatedUser())

现在 fetch 中的 fetch 和 dispatchers 工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多