Redux-thunk 异步操作 : Use custom middleware for async actions

标签 redux react-redux redux-thunk

我正在使用 redux-thunk用于异步操作和 babel-polyfill为了 promise 。我收到以下错误:Error: Actions must be plain objects. Use custom middleware for async actions.
我通过包含 redux-promise 解决了这个问题在我的中间件中。我不知道为什么我必须使用 redux-promise解决此问题,因为 Redux 文档中的所有示例都使用 babel-polyfill .我应该继续使用 redux-promise或者我可能对 babel-polyfill 有一些问题?
babel-polyfill包含在我的应用程序入口点中:

import 'babel-polyfill';

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import App from './components/App.jsx';
import store from './store.jsx';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.querySelector('.container'));

更新:

所以我检查以防万一我有 redux-thunk安装。它在我的 package.json 中。这是我的 store.js
import thunkMiddleware from 'redux-thunk';
import promise from 'redux-promise'

export default store = createStore(
  rootReducer,
  defaultState,
  applyMiddleware(
    thunkMiddleware,
    promise
  )
);

这是我在 action.js 中的异步操作:
function receiveStates(json) {
    return {
        type: RECEIVE_STATES,
        states: json.states,
    };
}

export function fetchStates(uuid) {
    return dispatch =>
        fetch(`https://my-api.com/session/${uuid}`)
        .then(response => response.json())
        .then(json => dispatch(receiveStates(json)));
}

这是我从组件调用操作的方式:
fetchStates(sessionID) {
    this.props.dispatch(fetchStates(sessionID));
}
# I bind this function in component's constructor 
this.fetchStates = this.fetchStates.bind(this);

最后,这是我的 reducer :
function statesReducer(state = null, action) {
    switch (action.type) {
        case RECEIVE_STATES:
            return { ...state, states: action.states };
        default:
            return state;
    }
}

最佳答案

我认为您的错误可能是由以下原因引起的:

  • 你没有从你的 Action 创建者那里返回一个 thunk(一个返回调度函数的函数),所以 Thunk 中间件不会捕获它(也许你正在返回一个 promise ?)
  • 您还没有按照 dzeno
  • 的建议安装 redux-thunk

    我建议您安装 redux-logger 中间件并将其作为最后一个添加到您的商店中间件中,删除返回 thunk 时不需要的 promise 中间件。
    通过这种方式,所有操作都记录在控制台中(前一个状态、当前操作、下一个状态),您可以调试您返回的未被 thunk 中间件“消化”的操作对象类型。

    关于Redux-thunk 异步操作 : Use custom middleware for async actions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38930963/

    相关文章:

    javascript - 智能组件和dumb组件之间的 React-Redux 数据流

    reactjs - 何时使用 componentWillReceiveProps 生命周期方法?

    javascript - 在 redux-thunk 中调用另一个异步函数

    unit-testing - 测试自定义 redux 中间件

    在第一次分派(dispatch)后 redux-observable 多个 Action

    javascript - 输入值未使用 react-admin 中的自定义输入更新

    javascript - Redux-React 通过 mapDispatchToProps 方法传递对象

    javascript - 如何比较两个 redux store 状态?

    reactjs - 决定从哪个 redux 容器进行 API 调用

    javascript - 如何在连接的 React-Redux 组件中测试 componentWillMount?