[英]Typescript complaining about React useState setter `Argument of type 'Dispatch<SetStateAction<never[]>>' is not assignable to parameter of
Presume I have this react component假设我有这个反应组件
export default function Restaurants() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetchUsers().then(setUsers);
})
...
and User.ts
is和
User.ts
是
interface User { name: string; }
export function fetchUsers(): Promise<User[]> { return fetch(...).then(r => r.json()) }
TypeScript is throwing Argument of type 'Dispatch<SetStateAction<never[]>>' is not assignable to parameter of type '(value: User[]) => void | PromiseLike<void>'. Types of parameters 'value' and 'value' are incompatible. Type 'IRestaurant[]' is not assignable to type 'SetStateAction<never[]>'. Type 'IRestaurant[]' is not assignable to type 'never[]'. Type 'IRestaurant' is not assignable to type 'never'.ts
TypeScript 正在抛出
Argument of type 'Dispatch<SetStateAction<never[]>>' is not assignable to parameter of type '(value: User[]) => void | PromiseLike<void>'. Types of parameters 'value' and 'value' are incompatible. Type 'IRestaurant[]' is not assignable to type 'SetStateAction<never[]>'. Type 'IRestaurant[]' is not assignable to type 'never[]'. Type 'IRestaurant' is not assignable to type 'never'.ts
Argument of type 'Dispatch<SetStateAction<never[]>>' is not assignable to parameter of type '(value: User[]) => void | PromiseLike<void>'. Types of parameters 'value' and 'value' are incompatible. Type 'IRestaurant[]' is not assignable to type 'SetStateAction<never[]>'. Type 'IRestaurant[]' is not assignable to type 'never[]'. Type 'IRestaurant' is not assignable to type 'never'.ts
I tried const [users, setUsers]: [User[], Function] = useState([]);
我试过
const [users, setUsers]: [User[], Function] = useState([]);
but that also didn't solve the issue How can I solve this issue?但这也没有解决问题我该如何解决这个问题?
You need TS to be able to infer at the time that you call useState
what sort of value it will contain.您需要 TS 能够在您调用
useState
时推断出它将包含什么样的值。
Since it's going to be an array of User
s, use that for the generic:由于它将是
User
的数组,因此将其用于泛型:
const [users, setUsers] = useState<User[]>([]);
I'd also highly recommend not ignoring errors - unhandled rejections should be avoided whenever possible.我还强烈建议不要忽略错误 - 应尽可能避免未经处理的拒绝。
fetchUsers()
.then(setUsers)
.catch(handleErrors);
You also probably only want to fetch the users once , rather than every time the component mounts.您也可能只想获取用户一次,而不是每次安装组件时。
useEffect(() => {
fetchUsers()
.then(setUsers)
.catch(handleErrors);
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.