반응형
반응 유형 스크립트 - 유형의 인수를 유형의 매개 변수에 할당할 수 없습니다.
데모가 있습니다.
Typescript와 훅을 사용하여 아래와 같이 간단한 형태로 엔트리를 캡처하는 리액트 앱입니다.
여기 Stackblitz에서는 동작합니다만, 로컬에서는 VS 코드를 사용하고 있기 때문에, 에러가 발생합니다.setUser(userData);
에러는
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)
이 타이프 스크립트 오류를 방지하려면 어떻게 해야 합니까?
const [user, setUser] = useState(null);
이것은 활자를 부여하지 않았기 때문에, 활자 원고가 추론해 보아야 합니다.null로 통과된 것을 인식하기 때문에 이 상태는 null로 간주됩니다(그리고 항상 null로 간주됩니다).대신 다음과 같이 유형을 지정해야 합니다.
interface UserData {
username: string;
password: string;
prevState: null
}
//...
const [user, setUser] = useState<UserData | null>(null);
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()
}, [])
언급URL : https://stackoverflow.com/questions/59125973/react-typescript-argument-of-type-is-not-assignable-to-parameter-of-type
반응형
'itsource' 카테고리의 다른 글
리액트 컴포넌트에서 외부 Javascript 함수를 호출합니다. (0) | 2023.03.23 |
---|---|
AJAX를 사용하여 인증 토큰을 Rails로 전송하는 적절한 방법 (0) | 2023.03.23 |
Javascript의 Moment js를 사용하여 ISO 8601을 날짜 및 시간 형식으로 해석하는 방법은 무엇입니까? (0) | 2023.03.23 |
네스트된 ng-repeat (0) | 2023.03.23 |
JSON 문자열을 저장하는 데 가장 적합한 SQL 데이터 유형은 무엇입니까? (0) | 2023.03.23 |