动作必须是普通对象 React 和 Redux 中的错误

Actions must be plain objects Error In React and Redux

我正在尝试在用户为项目投票时在通知中设置消息。

这是我遇到的错误,它发生在我单击按钮并调用我的 voteHandler 函数时。

×
Error: Actions must be plain objects. Use custom middleware for async actions.

这是函数,错误消息突出显示了我调用 setNotification 函数的行。

 const voteHandler = anecdote => {
    props.addVote(anecdote);
    const notification = `You voted for ${anecdote.content}`;
    props.setNotification(notification, 5);
  };

这是我的通知缩减程序:

const initialState = null;

const notificationReducer = (state = initialState, action) => {
  switch (action.type) {
    case "SET_NOTIFICATION":
      state = action.data;
      return state;
    case "REMOVE_NOTIFICATION":
      return initialState;
    default:
      return state;
  }
};

export const setNotification = (content, seconds) => {
  return dispatch => {
    dispatch({
      type: "SET_NOTIFICATION",
      content
    });
    setTimeout(() => {
      dispatch({
        type: "REMOVE_NOTIFICATION"
      });
    }, seconds * 1000);
  };
};

export const removeNotification = () => {
  return dispatch => {
    dispatch({
      type: "REMOVE_NOTIFICATION",
      notification: null
    });
  };
};

export default notificationReducer;

我一直在试验这个,如果我只将这个函数用于 setNotification,通知消息就会出现,因此看起来我调用 setTimeout 调用的方式可能有问题?

export const setNotification = (content, seconds) => {
  return {
    type: "SET_NOTIFICATION",
    data: content
  };
};

我还在学习 Redux,所以也许这是一个明显的错误,但我不确定。谢谢

export const setNotification = (content, seconds) => {
  return dispatch => {
    dispatch({
      type: "SET_NOTIFICATION",
      content
    });
    setTimeout(() => {
      dispatch({
        type: "REMOVE_NOTIFICATION"
      });
    }, seconds * 1000);
  };
};

问题应该出在上面的代码上。如果您希望从您的 redux 操作中 dispatch 多个 object,您将需要安装 Redux-Thunk。

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(rootReducer, applyMiddleware(thunk));