Redux-Thunk:动作必须是普通对象

时间:2020-02-28 21:05:24

标签: javascript reactjs redux react-redux redux-thunk

Redux thunk不适用于我,不确定为什么不这样做。以前,一切正常。现在,我正在尝试让redux-thunk起作用,但这只是给我

动作必须是普通对象

我认为我的代码相当标准:

createStore

import { createStore as reduxCreateStore, applyMiddleware } from 'redux';
import reducers from './src/reducers';

import reduxThunk from 'redux-thunk';

const createStore = () =>
  reduxCreateStore(reducers, {}, applyMiddleware(reduxThunk));
export default createStore;

将商店放入提供商

import React, { Component } from "react";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./src/reducers";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.store = createStore(reducer);
  }

  render() {
    return (
      <Provider store={this.store}>
        //...My App
      </Provider>
    );
  }
}

从React组件调用操作

import React, { Component } from "react";
import m from "mousetrap";
import { connect } from "react-redux";
import * as actions from "./src/actions";

class Mousetrap extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() { //binding the action to mousetrap hotkeys here
    m.bind(["space"], () => this.props.nextDiv());
  }
  //...
}

function mapStateToProps(state) {
  return {
    auth: state.auth,
  };
}

export default connect(mapStateToProps, actions)(Mousetrap);

动作创建者:

export const nextDiv = () => {
   return (dispatch, getState) => {
     dispatch({ type: NEXT_DIV });
  };
};

从到目前为止我在网上找到的信息来看,大多数人似乎在动作创建者发生错误时(例如,他们不返回函数等)时收到此错误-但我做得正确,我相信吗?

我认为在此步骤中可能出了点问题:

import * as actions from "./src/actions";
//...
export default connect(mapStateToProps, actions)(Mousetrap);

也许我不能像这样导入笨拙的动作创建者?还是我的绑定操作现在某种程度上无法与redux-thunk一起使用?抱歉问这个,我觉得这可能是微不足道的!提前非常感谢!

1 个答案:

答案 0 :(得分:2)

您没有使用createStore方法,而是再次从redux导入它。因此未添加中间件。

import React, { Component } from "react";
import { Provider } from "react-redux";
import { createStore } from "redux"; <--
import reducer from "./src/reducers";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.store = createStore(reducer);
  }

  render() {
    return (
      <Provider store={this.store}>
        //...My App
      </Provider>
    );
  }
}