【发布时间】:2019-07-02 07:06:35
【问题描述】:
我正在尝试了解如何将 TypeScript 与 useReducer 挂钩一起使用。这是一个使用常规 JavaScript 的简单计数器:
function reducer(state, action) {
switch (action.type) {
case "+":
return { ...state, no: state.no + 1}
case "-":
return { ...state, no: state.no - 1}
default:
throw new Error("All conditions missed");
}
}
function App() {
const [state, dispatch] = React.useReducer(reducer, {no: 1})
return (
<div className="App">
<h1>{state.no}</h1>
<button type="button" onClick={()=>dispatch({type: "-"})}>-</button>
<button type="button" onClick={()=>dispatch({type: "+"})}>+</button>
</div>
);
}
https://codesandbox.io/s/zealous-austin-eog2p
我尝试添加类型,但出现解析错误:
interface IState {
no: string;
}
function reducer(state: IState[], action) {
switch (action.type) {
case "+":
return { ...state, no: state.no + 1}
case "-":
return { ...state, no: state.no - 1}
default:
throw new Error("All conditions missed");
}
}
function App() {
const [state, dispatch] = React.useReducer(reducer, {no: 1}: IState[])
return (
<div className="App">
<h1>{state.no}</h1>
<button type="button" onClick={()=>dispatch({type: "-"})}>-</button>
<button type="button" onClick={()=>dispatch({type: "+"})}>+</button>
</div>
);
}
【问题讨论】:
标签: reactjs typescript