我目前正在開發一個計算器來與打字稿做出反應,但我在我的減速器函式中輸入狀態時遇到了一些問題。目前只有“任何”有效。我知道這是一個里面有字串的物件,但我不知道為什么它不起作用。
謝謝你的幫助。
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;
uj5u.com熱心網友回復:
您的 switch 陳述句并不詳盡。在默認情況下,您什么都不回傳。
像這樣更改減速器功能:
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;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377274.html
