![](/img/trans.png)
[英]Typescript/React-Native: Argument of type 'string | null' is not assignable to parameter of type 'SetStateAction<never[]>'
[英]Typescript complaining about React useState setter `Argument of type 'Dispatch<SetStateAction<never[]>>' is not assignable to parameter of
假設我有這個反應組件
export default function Restaurants() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetchUsers().then(setUsers);
})
...
和User.ts
是
interface User { name: string; }
export function fetchUsers(): Promise<User[]> { return fetch(...).then(r => r.json()) }
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
我試過const [users, setUsers]: [User[], Function] = useState([]);
但這也沒有解決問題我該如何解決這個問題?
您需要 TS 能夠在您調用useState
時推斷出它將包含什么樣的值。
由於它將是User
的數組,因此將其用於泛型:
const [users, setUsers] = useState<User[]>([]);
我還強烈建議不要忽略錯誤 - 應盡可能避免未經處理的拒絕。
fetchUsers()
.then(setUsers)
.catch(handleErrors);
您也可能只想獲取用戶一次,而不是每次安裝組件時。
useEffect(() => {
fetchUsers()
.then(setUsers)
.catch(handleErrors);
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.