【问题标题】:Redux-Thunk : Actions must be plain objectsRedux-Thunk:动作必须是普通对象
【发布时间】:2020-06-13 00:01:31
【问题描述】:

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;

将 store 放入 Provider

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 组件调用 Action

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);

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

【问题讨论】:

  • 首先观察到,您的nextDiv 函数不需要是当前编写的thunk。它可能只是const nextDiv = () =&gt; ({type: "NEXT_DIV"})。其次,我建议在浏览器的 DevTools 中的 Redux createStore 函数的代码中设置一个断点,看看实际值达到了多少 dispatch。第三,我强烈建议using our official Redux Toolkit package 设置商店而不是手工操作。
  • 非常感谢,马克。我一直在阅读您的很多帖子,非常感谢您的工作!我知道我在这里不需要 thunk,我只是想弄清楚问题出在哪里,所以我简化了一些事情。我去看看 redux toolkot 包,谢谢!

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


【解决方案1】:

您没有使用 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>
    );
  }
}

【讨论】:

  • 非常感谢您发现这一点!不敢相信它是如此微不足道!谢谢!!
猜你喜欢
  • 2018-03-23
  • 1970-01-01
  • 2019-11-11
  • 2018-07-08
  • 2017-11-28
  • 2023-03-14
  • 2017-05-09
  • 1970-01-01
相关资源
最近更新 更多