反应TypeScript:使用useReducer时出现TS错误

时间:2019-12-10 12:26:18

标签: 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 <>{count}<button onClick={handleClick}>Click Me</button></>;
}

这是@types/react中的错误吗?

我认为应该是:

type Dispatch<A> = (value?: A) => void;

代替

type Dispatch<A> = (value: A) => void;

1 个答案:

答案 0 :(得分:1)

分派函数始终需要一个操作,该操作应该是化简器中的第二个参数:

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);
}