首页 > 解决方案 > React TypeScript:使用 useReducer 时出现 TS 错误

问题描述

这是我的代码:

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;

标签: reactjstypescriptdefinitelytyped

解决方案


一个调度函数总是需要一个动作,它应该是你减速器中的第二个参数:

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 参考 (useReducer)

对于您的情况,我建议使用 auseState代替:

const [count, setCount] = useState(0);
const increase = () => {
  setCount(prev => prev + 1);
}

推荐阅读