Reactjs 反应类型脚本:使用useReducer时出错
这是我的密码:Reactjs 反应类型脚本:使用useReducer时出错,reactjs,typescript,definitelytyped,Reactjs,Typescript,Definitelytyped,这是我的密码: const Component = () => { const [count, increase] = useReducer(v => v + 1, 0); const handleClick = useCallback( () => { // TS2554: Expected 1 arguments, but got 0. increase(); }, [] ); return <>{
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></>;
}
而不是
type Dispatch<A> = (value: A) => void;
type Dispatch=(值:A)=>void;
分派函数总是需要一个动作,这应该是减速机中的第二个参数:
const [count, increase] = useReducer((v, action) => v + 1, 0);
原因是您可以切换操作。键入并相应地处理每个案例。例如:
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' });
这就是为什么分派需要一个参数。更多信息:
对于您的情况,我建议使用useState
:
const [count, setCount] = useState(0);
const increase = () => {
setCount(prev => prev + 1);
}
是的,是吗?指出它可以在没有参数的情况下调用useState
不够好,因为每次呈现时增量都会改变。useReducer
没有更多的功能,它只是使useState
的复杂用例更容易推理。它们的核心是相同的。你想要实现什么?每次单击按钮时,只需将数字增加1?使用useState
查看我的示例。
const [count, setCount] = useState(0);
const increase = () => {
setCount(prev => prev + 1);
}