【问题标题】:Actions must be plain objects. React-redux error动作必须是普通对象。反应减少错误
【发布时间】:2022-01-04 22:30:40
【问题描述】:

因此,我不知道为什么会遇到此错误,我已经查看了所有表格并尝试构建我的操作以表示正确的结构,但我仍然遇到此错误。有人可以帮我调试一下吗?

这里是动作:

export const listProjects =
  (pageNumber = "") =>
  async (dispatch) => {
    try {
      // Dispatch request type
      dispatch(PROJECT_LIST_REQUEST);
      // axios call
      const { data } = await axios({
        method: "GET",
        url: `/api/projects?page=${pageNumber}`,
      });
      // on success dispatch request success
      dispatch({
        type: PROJECT_LIST_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: PROJECT_LIST_FAIL,
        payload:
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message,
      });
    }
  };

这里是store

import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";

// import reducers
import { userLoginReducer } from "./reducers/userReducer";
import { projectListReducer } from "./reducers/projectsReducer";

const middleware = [thunk];

const reducer = combineReducers({
  userLogin: userLoginReducer,
  getProjects: projectListReducer,
});

const userInfoFromStorage = localStorage.getItem("userInfo")
  ? JSON.parse(localStorage.getItem("userInfo"))
  : null;

const initialState = {
  userLogin: { userInfo: userInfoFromStorage },
};
const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;

这里是调用动作以从 API 返回数据的 useEffect

useEffect(() => {
    dispatch(listProjects(page));
  }, [dispatch, page]);

我有一个较早的项目,其中代码的结构相似,但是,我只是不明白我做错了什么。

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

    看起来在您的 listProjects 函数中,您正在调度一个变量而不是一个动作 (dispatch(PROJECT_LIST_REQUEST);),而在其他函数中,您正在调度一个动作对象,但类型是变量/常量。

    您是否将PROJECT_LIST_REQUEST / PROJECT_LIST_SUCCESS / PROJECT_LIST_FAIL 保存为该文件中的变量/常量?

    通常您会使用字符串进行调度,因此将其更改为 dispatch({type: 'PROJECT_LIST_REQUEST'}) 应该可以解决错误,尽管您可能还需要将其他字符串转换为字符串:

    dispatch({type: 'PROJECT_LIST_REQUEST'})
    ...
    dispatch({
        type: 'PROJECT_LIST_SUCCESS',
        payload: data,
    }); 
    ...
    dispatch({
        type: 'PROJECT_LIST_FAIL',
        payload:
            error.response && error.response.data.message
            ? error.response.data.message
            : error.message,
    });
    

    【讨论】:

    • 是的!实际上我正要评论说我想通了哈哈。我一直在查看我的代码和论坛,试图找出哪里出错了,但我认为这与函数的异步部分有关,而不是调度本身。感谢您的回答,我会将您的答案标记为正确答案!
    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 2020-06-13
    • 2018-03-23
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多