[英]React Typescript - Argument of type is not assignable to parameter of type
It's a React app using Typescript and hooks to capture entries into form that are simple displayed below.这是一个 React 应用程序,使用 Typescript 和钩子将条目捕获到下面简单显示的表单中。
Here in Stackblitz it works but locally I am using VS code and I get an error for setUser(userData);
在 Stackblitz 中,它可以工作,但在本地我使用的是 VS 代码,我收到
setUser(userData);
the error is错误是
const userData: {
username: string;
password: string;
prevState: null;
}
Argument of type '{ username: string; password: string; prevState: null; }' is not assignable to parameter of type '(prevState: null) => null'.
Type '{ username: string; password: string; prevState: null; }' provides no match for the signature '(prevState: null): null'.ts(2345)
How can I fox this typescript error我怎样才能解决这个打字稿错误
const [user, setUser] = useState(null);
Since you havn't given this a type, typescript has to try to infer it.因为你没有给它一个类型,typescript 必须尝试推断它。 It sees you passed in a null, so it assumes this state is (and always will be) null.
它看到您传入了一个空值,因此它假定此状态为(并且始终为)空值。 Instead, you need to specify the type, as in:
相反,您需要指定类型,如:
interface UserData {
username: string;
password: string;
prevState: null
}
//...
const [user, setUser] = useState<UserData | null>(null);
If you fetching data from API you need this:如果你从 API 获取数据,你需要这个:
import React, { useState, useEffect } from 'react'
import axios from 'axios';
const MyComponent = () => {
const [data, setData] = useState<any | null>(null);
const fetchData = () => {
(...) //Axios.get() or async if u await data.
setData(fetchData)
}
}
useEffect(() =>{
fetchData()
}, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.