这是我的代码:
const Component = () => {
const [count, increase] = useReducer(v => v + 1, 0);
const handleClick = useCallback(
() => {
// TS2554: Expected 1 arguments, but got 0.
increase();
},
[]
);
return <>{count}<button onClick={handleClick}>Click Me</button></>;
}
这是
@types/react
中的一些错误吗? ?我觉得应该是:
type Dispatch<A> = (value?: A) => void;
代替
type Dispatch<A> = (value: A) => void;
最佳答案
dispatch 函数总是需要一个 action,它应该是你的 reducer 中的第二个参数:
const [count, increase] = useReducer((v, action) => v + 1, 0);
原因是你可以切换
action.type
并相应地处理每个案例。例如:const [count, dispatch] = useReducer((state, action) => {
switch(action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
return state;
}
}, 0);
然后你称之为:
dispatch({ type: 'increment' });
这就是为什么 dispatch 需要一个参数。更多信息:Hooks API Reference (useReducer)
对于您的情况,我建议使用
useState
反而:const [count, setCount] = useState(0);
const increase = () => {
setCount(prev => prev + 1);
}
关于reactjs - react typescript : TS Error when using useReducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59267210/