简体   繁体   English

React TypeScript:使用 useReducer 时出现 TS 错误

[英]React TypeScript: TS Error when using useReducer

Here is my code:这是我的代码:

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

Is this some bug in @types/react ?这是@types/react一些错误吗?

I think it should be:我觉得应该是:

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

instead of代替

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

A dispatch function always needs an action, which should be your second parameter in your reducer: dispatch 函数总是需要一个 action,它应该是你的 reducer 中的第二个参数:

const [count, increase] = useReducer((v, action) => v + 1, 0);

The reason being so you can switch over action.type and handle each case accordingly.原因是你可以切换action.type并相应地处理每个案例。 For example:例如:

const [count, dispatch] = useReducer((state, action) => {
  switch(action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    default:
      return state;
  }
}, 0);

And then you call it like:然后你称之为:

dispatch({ type: 'increment' });

That's why dispatch requires one argument.这就是为什么 dispatch 需要一个参数。 More information: Hooks API Reference (useReducer)更多信息: Hooks API 参考 (useReducer)

For your case I suggest using a useState instead:对于您的情况,我建议改用useState

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM