【问题标题】:React TypeScript: TS Error when using useReducerReact TypeScript:使用 useReducer 时出现 TS 错误
【发布时间】:2020-04-03 15:19:39
【问题描述】:

这是我的代码:

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;

【问题讨论】:

  • 是的,?表示可以不带参数调用

标签: reactjs typescript definitelytyped


【解决方案1】:

一个调度函数总是需要一个动作,它应该是你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);
}

【讨论】:

  • useState 不够好,因为每次渲染时增加都会改变。
  • useReducer 没有更多功能,它只是让useState 的复杂用例更容易推理。他们的核心是相同的。你想达到什么目标?每次单击按钮时只需将数字加 1?查看我使用useState 的示例。
猜你喜欢
  • 2019-12-15
  • 2023-01-23
  • 2019-12-09
  • 2019-09-20
  • 2021-04-21
  • 1970-01-01
  • 2021-11-13
  • 2021-04-18
  • 2021-05-26
相关资源
最近更新 更多