javascript - Redux-Thunk - 异步 Action 创建者 promise 和链接不起作用

标签 javascript reactjs redux redux-thunk redux-promise

我正在尝试发送一个 Action 。我找到了一些操作的工作示例,但没有我的那么复杂。

你能给我一个提示吗?我做错了什么?

我正在使用 TypeScript,最近删除了所有类型并尽可能简化了我的代码。

我正在使用 redux-thunk 和 redux-promise,像这样:

import { save } from 'redux-localstorage-simple';
import thunkMiddleware from 'redux-thunk';
import promiseMiddleware from 'redux-promise';

const middlewares = [
        save(),
        thunkMiddleware,
        promiseMiddleware,
    ];
const store = createStore(
        rootReducer(appReducer),
        initialState,
        compose(
            applyMiddleware(...middlewares),
            window['__REDUX_DEVTOOLS_EXTENSION__'] ? window['__REDUX_DEVTOOLS_EXTENSION__']() : f => f,
        ),
    );

组件 - Foo 组件:

import actionFoo from 'js/actions/actionFoo';
import React, { Component } from 'react';
import { connect } from 'react-redux';

class Foo {
    constructor(props) {
        super(props);
        this._handleSubmit = this._handleSubmit.bind(this);
    }
    _handleSubmit(e) {
        e.preventDefault();
        this.props.doActionFoo().then(() => {
            // this.props.doActionFoo returns undefined
        });
    }
    render() {
        return <div onClick={this._handleSubmit}/>;
    }
}

const mapStateToProps = ({}) => ({});

const mapDispatchToProps = {
    doActionFoo: actionFoo,
};

export { Foo as PureComponent };
export default connect(mapStateToProps, mapDispatchToProps)(Foo);

Action - actionFoo:

export default () => authCall({
    types: ['REQUEST', 'SUCCESS', 'FAILURE'],
    endpoint: `/route/foo/bar`,
    method: 'POST',
    shouldFetch: state => true,
    body: {},
});

操作 - AuthCall:

// extremly simplified
export default (options) => (dispatch, getState) => dispatch(apiCall(options));

操作 - ApiCall:

export default (options) => (dispatch, getState) => {
    const { endpoint, shouldFetch, types } = options;

    if (shouldFetch && !shouldFetch(getState())) return Promise.resolve();

    let response;
    let payload;

    dispatch({
        type: types[0],
    });

    return fetch(endpoint, options)
        .then((res) => {
            response = res;
            return res.json();
        })
        .then((json) => {
            payload = json;

            if (response.ok) {
                return dispatch({
                    response,
                    type: types[1],
                });
            }
            return dispatch({
                response,
                type: types[2],
            });
        })
        .catch(err => dispatch({
            response,
            type: types[2],
        }));
};

最佳答案

来自 redux-thunk

Redux Thunk middleware allows you to write action creators that return a function instead of an action

所以这意味着它不处理您的 promise 。您必须添加 redux-promise promise 支持

The default export is a middleware function. If it receives a promise, it will dispatch the resolved value of the promise. It will not dispatch anything if the promise rejects.

redux-thunkredux-promise 之间的区别你可以阅读 here

关于javascript - Redux-Thunk - 异步 Action 创建者 promise 和链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48103565/

相关文章:

javascript - 带有 Angular/ ionic 中断布局的 anchor 滚动不再可能向上滚动

javascript - NVelocity 高级循环语法

reactjs - this.props.data 不是一个函数

javascript - 在异步函数中执行 createStore 时未定义存储?

javascript - 下一个 js : next auth provider + redux provider

javascript - 如何在应用制作工具查询中引用值(就像在 Apps 脚本中一样)

javascript - 表排序器 : table. config.parsers[c] 未定义

javascript - react-create-app - 获取有关浏览器列表错误的错误

javascript - 在 react.js 中扩展样式对象

javascript - 等待响应再返回