输入 useReducer 的状态

Typing the state of useReducer

我目前正在开发一个与打字稿反应的计算器,但在我的 reducer 函数中输入状态时遇到了一些问题。 目前只有“任何”有效。 我知道那是一个内部有字符串的对象,但我不知道为什么它不起作用。

感谢您的帮助。

import { useReducer } from "react";
import Grid from "./components/Grid";
import NumberButton from "./components/NumberButton";
import OperatorButton from "./components/OperatorButton";

// type State = {
//   currentOperation?: string
//   result?: string
//   operator?: string
// }

export enum ACTIONS {
  ADD_NUMBER = 'add-number',
  ADD_OPERATOR = 'add-operator',
  CALCULATE = 'calculate',
  DELETE = 'delete',
  RESET = 'reset'
}

export type Action = {
  type: ACTIONS,
  payload?: { digit?: string, operator?: string }
}

const reducer = (state: any, { type, payload }: Action) => {

  console.log("State", state);

  switch (type) {
    case ACTIONS.ADD_NUMBER:
      return {
        ...state,
        currentOperation: `${state.currentOperation || ""}${payload!.digit}`
      };

   
    default:
      break;
  }
};

const App = () => {

  const [{ currentOperation, result, operator }, dispatch] = useReducer(reducer, {});

  return (
    <Grid>
      <div className="displayScreen">
        <div className="currentOperation">{currentOperation} {operator}</div>
        <div className="result">{result}</div>
      </div>
      <button onClick={() => dispatch({ type: ACTIONS.RESET })}>C</button>
    </Grid>
  )
}

export default App;

您的 switch 语句并不详尽。在默认情况下,您什么都不返回。

像这样更改 reducer 函数:

const reducer = (state: State, { type, payload }: Action) => {

然后:

default: 
  return state;

这应该有效。

不使用枚举来键入操作的另一种方法:

type State = {
  currentOperation?: string
  result?: string
  operator?: string
}
export type Action = 
   | { type: 'ADD_NUMBER', payload: {digit: number} }
   | { type: 'ADD_OPERATOR', payload: string};

const reducer = (state: State, action: Action) => {
  console.log("State", state);
  switch (action.type) {
    case 'ADD_NUMBER':
      return {
        ...state,
        currentOperation: `${state.currentOperation || ""}${action.payload.digit}`
      };
    case 'ADD_OPERATOR':
      return {
        ...state,
        // (payload here is a string)
      }
   
    default:
      return state;
  }
};