簡體   English   中英

react-redux 錯誤:操作必須是普通對象。 使用自定義中間件進行異步操作

[英]react-redux Error: Actions must be plain objects. Use custom middleware for async actions

我有一個非常簡單的代碼,用於在按下 + 或 - 按鈕時遞增和遞減。 但每當我按下按鈕時,我都會收到錯誤消息。 我已經研究了大約 4 個小時,但找不到原因。 我很確定我沒有執行任何異步操作並且我的操作正在返回 JavaScript 對象

動作代碼:

export const increment = () => {
    return { type: 'INCREMENT' }
}

export const decrement = () => {
    return { type: 'DECREMENT' }
}

減速機代碼:

export default function counterReducer(state = 0, action) {
    switch (action.type) {
      case 'INCREMENT':
        return state + 1
      case 'DECREMENT':
        return state - 1
      default:
        return state
    }
  }

應用組件代碼:

import React from "react";
import {decrement, increment } from "./actions";
import { useSelector, useDispatch } from "react-redux";
export default function App() {
  const counter = useSelector((state) => state.counter);
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={() => dispatch(increment)}>+</button>
      <button onClick={() => dispatch(decrement)}>-</button>
      <p>{counter}</p>
    </div>
  );
}

非常感激。

在 Redux 中, 動作是對象 你必須在 dispatch(increment) 中執行 action 函數: dispatch(increment)可以是dispatch(increment())

您正在調度動作創建者功能而不是動作

遞增和遞減函數稱為動作創建者。 他們返回操作 object。

您應該調用動作創建者 function 來調度動作。

<button onClick={() => dispatch(**increment()**)}>+</button>

這個問題可以通過在 store 配置中使用像redux-thunksaga這樣的中間件來解決。

import { createStore, applyMiddleware } from "redux";

import rootReducer from "../reducers";
import thunk from "redux-thunk";

//Applying redux-thunk solves the problem
//Actions must be plain objects. Use custom middleware for async actions.

export const store = createStore(rootReducer, applyMiddleware(thunk));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM