reactjs - 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;
解决方案
一个调度函数总是需要一个动作,它应该是你减速器中的第二个参数:
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);
}
推荐阅读
- r - 如何使用 tidyverse 根据日期条件从同一表内的列表中将行带到我的表中?
- python-3.x - 在 300k 行数据集上绘制真的很慢
- python - python中的组
- r - 将数据映射到自定义公式函数
- matlab - 寻找艾伦偏差单位
- arrays - 如何让程序不计算数学表达式?
- css - Bootstrap Sticky 在容器中全宽
- javascript - QuerySelector 返回 null。如何让 querySelector 返回
- list - 作为 Flutter 中另一个类的参数的类列表
- android - 有没有办法在不更改 App ID 的情况下同时安装 Flutter 应用的调试版本和发布版本?