【问题标题】:Redux-thunk async actions: Use custom middleware for async actionsRedux-thunk 异步操作:使用自定义中间件进行异步操作
【发布时间】:2016-12-20 05:38:39
【问题描述】:

我将redux-thunk 用于异步操作,babel-polyfill 用于承诺。我收到以下错误: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);

最后,这是我的减速器:

function statesReducer(state = null, action) {
    switch (action.type) {
        case RECEIVE_STATES:
            return { ...state, states: action.states };
        default:
            return state;
    }
}

【问题讨论】:

标签: redux react-redux redux-thunk


【解决方案1】:

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

  1. 您没有从动作创建者返回一个 thunk(一个返回调度函数的函数),因此 Thunk 中间件不会捕获它(也许您正在返回一个承诺?)
  2. 你没有按照 dzeno 的建议安装 redux-thunk

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

【讨论】:

  • 确实,在我的情况下,我返回的是一个承诺而不是一个重击
【解决方案2】:

听起来你还没有安装/设置redux-thunk

你以通常的方式安装 npm 包:

npm install --save redux-thunk

这里是一个应用redux-thunk中间件的例子

getStore.js

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

const getStore = ({combined, initial}) =>{
    var store = createStore(combined, initial, applyMiddleware(thunk))
    return store
}

export{
    getStore
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2018-01-30
    • 2018-01-31
    • 2017-03-03
    • 2018-09-21
    • 2021-10-04
    相关资源
    最近更新 更多