将API调用数据设置为状态,但在分配类型时遇到问题
我正在使用NASA API构建一个简单的打字稿项目。首先,我只是在我的erach.tsx
组件中向单个对象提出get请求,然后尝试将数据渲染到浏览器。
API数据被保存到状态:
{
date: '2018-01-03T16:50:46.890000',
id: 'LANDSAT/LC08/C01/T1_SR/LC08_025039_20180103',
resource: {…},
service_version: 'v5000',
url: 'https://earthengine.googleapis.com/v1alpha/project…bccd48-3aa76fabdd69b028540a8edb2800e72b:getPixels'
}
问题是,当我尝试渲染数据时,我会得到错误
对象可能是未定义的
对如何解决此问题有任何建议?我有一种与我对状态相关的类型有关的。
Earth.tsx
import { useState, useEffect,FC } from "react"
import axios, { AxiosResponse } from "axios"
const Earth = ():JSX.Element => {
interface IEarth {
date:string,
id:string,
resource:{
dataset:string,
planet:string
}
service_version: string,
url: string
}
// type PhotoPayload = IEarth[]
const [data,setData] = useState<IEarth>()
const url = 'https://api.nasa.gov/planetary/earth/assets?lon=-95.33&lat=29.78&date=2018-01-01&&dim=0.10&api_key=DEMO_KEY'
const getData = ():void => {
axios.get(url)
.then((res: AxiosResponse) => {
setData(res.data)
})
}
useEffect(() => {
getData()
},[])
console.log('data', data)
return(
<div>
{data.url}
</div>
)
}
export default Earth
I'm building a simple TypeScript project using the NASA API. To begin with I'm simply making a get request for a single object in my Earth.tsx
component, and then trying to render the data to the browser.
API data being saved to state:
{
date: '2018-01-03T16:50:46.890000',
id: 'LANDSAT/LC08/C01/T1_SR/LC08_025039_20180103',
resource: {…},
service_version: 'v5000',
url: 'https://earthengine.googleapis.com/v1alpha/project…bccd48-3aa76fabdd69b028540a8edb2800e72b:getPixels'
}
The problem is that when I try to render the data, I get the error
Object is possibly undefined
Any suggestions on how to fix this? I have a feeling it's to do with the type I've assgined to my state.
Earth.tsx
import { useState, useEffect,FC } from "react"
import axios, { AxiosResponse } from "axios"
const Earth = ():JSX.Element => {
interface IEarth {
date:string,
id:string,
resource:{
dataset:string,
planet:string
}
service_version: string,
url: string
}
// type PhotoPayload = IEarth[]
const [data,setData] = useState<IEarth>()
const url = 'https://api.nasa.gov/planetary/earth/assets?lon=-95.33&lat=29.78&date=2018-01-01&&dim=0.10&api_key=DEMO_KEY'
const getData = ():void => {
axios.get(url)
.then((res: AxiosResponse) => {
setData(res.data)
})
}
useEffect(() => {
getData()
},[])
console.log('data', data)
return(
<div>
{data.url}
</div>
)
}
export default Earth
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用“ nofollow noreferrer”>可选链接 in
{data.url}
,因此{data?.url}
Use optional chaining
?.
in{data.url}
, so it becomes{data?.url}