TypeScript是新手,我想知道在将axios响应保存到状态变量时如何键入它?
我正在从中进行一个简单的API调用
App.tsx
,返回以下对象:
{data: {â¦}, status: 200, statusText: 'OK', headers: {â¦}, config: {â¦}, â¦}
config: {//////}
data: {copyright: 'Dietmar Hager', date: '2022-02-26', explanation: 'Large spiral galaxy NGC 4945 is seen nearly edge-oâ¦xy and home to a central supermassive black hole.', hdurl: 'https://apod.nasa.gov/apod/image/2202/NGC4945-Dietmar-Eric-crop.jpg', media_type: 'image', â¦}
headers: {////}
request: XMLHttpRequest {///}
status: 200
statusText: "OK"
[[Prototype]]: Object
我正在访问
data
r此对象的属性,然后将其设置为状态:
{copyright: 'Dietmar Hager',.....',
hdurl: 'https://apod.nasa.gov/apod/image/2202/NGC4945-Dietmar-Eric-crop.jpg', media_type: 'image', â¦}
copyright: "Dietmar Hager"
date: "2022-02-26"
explanation: "Large spiral galaxy NGC 4945 ......"
hdurl: "https://apod.nasa.gov/apod/image/2202/NGC4945-Dietmar-Eric-crop.jpg"
media_type: "image"
title: "Nearby Spiral Galaxy NGC 4945"
url: "......"
[[Prototype]]: Object
考虑到响应是一个对象,我认为应该将初始状态设置为空对象,但出现了以下错误
类型“{}”上不存在属性“map”
有没有关于如何输入axios响应的建议?
以下是目前为止的项目:
应用程序。tsx
import React, { useEffect, useState } from 'react';
import axios, { AxiosResponse } from 'axios'
function App(): JSX.Element {
const [ photo,setPhoto ] = useState({})
const getData = async (): Promise<void> => {
await axios.get('https://api.nasa.gov/planetary/apod?api_key=*********')
.then((response: AxiosResponse) => {
console.log(response)
setPhoto(response.data)
})
}
console.log(photo)
useEffect(() => {
getData()
},[])
return (
<div>
{photo.map(x => {console.log(x)})}
</div>
);
}
export default App;
我还想到,我应该将对象的每个单独元素的类型设置为接口,但这似乎是一种笨拙的操作方式:
function App(): JSX.Element {
interface State {
url:string
}
const [ photo,setPhoto ] = useState<State>({})
const getData = async (): Promise<void> => {
await axios.get('https://api.nasa.gov/planetary/apod?api_key=*********')
.then((response: AxiosResponse) => {
console.log(response)
setPhoto({url:response.data.url})
})
}