'未捕获的错误:操作必须是普通对象,使用定制中间件处理Redux-toolkit中的异步操作错误

mjqavswn  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(114)

计算器切片代码计算器Slice.js

const initialState = {
  display: 0,
  currentOperand: null,
  previousOperand: null,
  currentOperator: null
};

export const calculatorSlice = createSlice({
  name: 'calculator',
  initialState,
  reducers: {
    getDisplay (state) {
      return state.display;
    },
    enterDigit (state, action) {
      if (state.display !== '0') {
        [ ...state.display ].concat(action.payload);
      }
      else {
        state.display = action.payload;
      }
      state.currentOperand = parseFloat(state.display);
    }
  }
});

This is the image of the error
在此处调度操作app.js

import { useSelector, useDispatch } from 'react-redux';
import { enterDigit, getDisplay } from './features/calculatorSlice';

const App = () => {
  const state = useSelector(state => state.calculator);

  return (
    <div className="container">
      <div className="top-container">
        <h1>{state.display}</h1>
      </div>
      <div className="bottom-container">
        <button onClick={useDispatch(enterDigit('1'))}>1</button>
      </div>
    </div>
  );
};

export default App;

当我点击值为1的按钮时,什么也没有发生。state.display没有更新,也给了我上面提到的错误。

r1zhe5dt

r1zhe5dt1#

您无法调度不是普通Javascript对象的操作。.尝试按如下方式更新代码:

import { useDispatch } from 'react-redux';
import { enterDigit } from './features/calculatorSlice';

const App = () => {
  const dispatch = useDispatch();
  const state = useSelector(state => state.calculator);

  return (
    <div className="container">
      <div className="top-container">
        <h1>{state.display}</h1>
      </div>
      <div className="bottom-container">
        <button onClick={() => dispatch(enterDigit('1'))}>1</button>
      </div>
    </div>
  );
};

export default App;

相关问题