【问题标题】:Typing the state of useReducer输入 useReducer 的状态
【发布时间】:2022-01-12 23:45:42
【问题描述】:

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

感谢您的帮助。

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;

【问题讨论】:

    标签: reactjs typescript types use-reducer


    【解决方案1】:

    您的 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;
      }
    };
    

    【讨论】:

    • 非常感谢,我错过了退货部分
    • @Sam 如果它适合你,请不要忘记接受这个答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多