类型为"number"的参数不能分配给类型为"SetStateAction<{ count1: number; count2: number; }>



我尝试用typescript实现计数器,但我得到错误说:

"类型'number'的参数不能分配给类型'SetStateAction<{count1: number;是从:数量;}祝辞的"。
当我点击按钮时,p标签会消失。

下面是代码,我用粗体突出显示了有错误的部分:

import React, { useState } from "react";


export const UseStateP: React.FC = () => {
const [{count1,count2}, setCount] = useState ({count1:0, count2:5});
console.log(count1,count2) // 0, 5
return (
<div>
<p>{count1}</p>
<p>{count2}</p>
<button onClick={() => setCount(count1+1)}>Add1</button>
<button onClick={() => setCount(count2+5)}>Add5</button>
</div>
);
};

因为你的状态是对象。所以你需要更新setCount来更新对象

setCount((preState) => ({
...preState,
count1: count1 + 1,
}));

出现错误是因为从这一行setCount(count1+1)setCount(count2+5)

你的原始状态期望有一个count1count2的对象,但是当你设置你的状态时,你只给出一个。

所以解决方案是把这两个变量从你的原始状态,像这样:

onClick={() => setCount({ count1: count1 + 1, count2 })}

所以整个组件变成:

export const UseStateP: React.FC = () => {
const [{ count1, count2 }, setCount] = useState<{
count1: number;
count2: number;
}>({ count1: 0, count2: 5 });
return (
<div>
<p>{count1}</p>
<p>{count2}</p>
<button
type="button"
onClick={() => setCount({ count1: count1 + 1, count2 })}
>
Add1
</button>
<button
type="button"
onClick={() => setCount({ count1, count2: count2 + 5 })}
>
Add5
</button>
</div>
);
};

另外,记得把button type作为HTML标准的按钮元素

和Viet的答案也是另一个更短的解决方案,以满足打字期望和修复类型错误。

相关内容

最新更新