数据正在从 API 成功返回。这是我第一次使用 TypeScript 调用 API。我遇到的问题是我不确定我的接口(interface)是否成功验证了 API 数据。
const App = () => {
const [userData, setUserData] = useState<User[]>([])
console.log('User data: ', userData);
useEffect(() => {
axios
.get<User[]>('https://jsonplaceholder.typicode.com/users')
.then((response) => {
setUserData(response.data)
})
.catch(error => console.log(error.message))
}, [])
return ...
};
export default App;
这是我的界面
export interface User {
id: number,
name: string,
username: string,
email: string,
address: Address,
phone: string,
website: string,
company: Company,
}
export interface Address {
street: string,
suite: string,
city: string,
zipcode: string,
geo: Geolocation,
}
export interface Geolocation {
lat: string,
lng: string,
}
export interface Company {
name: string,
catchPhrase: string,
bs: string,
}
最佳答案
如果您不确定界面中的 Prop 是否有数据。你可以使用这个语法 接口(interface) your_interface_name { your_props_name?: type_data
例如:export interface Geolocation { lat?: string, lng?: string, }
关于reactjs - 如何使用 TypeScript 验证与 Axios GET 响应的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65501942/