[英]How do I access React State properties using TypeScript? Get property does not exist on type error
I have defined a type, I get the expected data from my API.我已经定义了一个类型,我从我的 API 中获得了预期的数据。 However, when I try access a property I get error
Property 'deployed' does not exist on type 'Service[]'.
但是,当我尝试访问一个属性时,我收到错误
Property 'deployed' does not exist on type 'Service[]'.
. . I'm confused because deployed is a property?
我很困惑,因为部署是一个财产?
Here is my type:这是我的类型:
export interface Service {
service: String,
deployed: String,
message: String[]
}
Here is API request:这是 API 请求:
import axios from 'axios';
import { apiBaseURL } from '../constants';
import { Service } from '../types'
export const getStatus = async () => {
const { data: status } = await axios.get<Service[]>(`${apiBaseURL}/status`);
return status;
}
Code with error:有错误的代码:
import React from 'react';
import './App.css';
import { getStatus } from './services/status';
import { Service } from './types';
function App() {
const [status, setStatus] = React.useState<Service[]>([]);
React.useEffect(() => {
(async () => {
const response = await getStatus();
setStatus(response);
console.log(status);
})()
// eslint-disable-next-line
}, [])
return (
<div className="App">
<header className="App-header">
<h1>App</h1>
</header>
{status && (
<p>{status.deployed}</p>
)}
</div>
);
}
export default App;
Service[]
is an array. Service[]
是一个数组。 The array type does not have a property called deployed
数组类型没有名为已
deployed
的属性
This line:这一行:
const [status, setStatus] = React.useState<Service[]>([]);
Says, status
is a an array of Service
.说,
status
是一个Service
数组。
This line:这一行:
<p>{status.deployed}</p>
Says, you want access deployed
method of that array.说,您想要访问该数组的已
deployed
方法。 Which is wrong.这是错误的。
A possible way to check whether this hypothesis is right, would be to try to access deployed
on an element of that array.检查此假设是否正确的一种可能方法是尝试访问
deployed
在该数组的元素上。
For example, assuming you have validated that there exists at least one element in status
array, this:例如,假设您已验证
status
数组中至少存在一个元素,则:
<p>{status[0].deployed}</p>
or if you wanted to print all the deployed status, something like this:或者,如果您想打印所有已部署的状态,如下所示:
{!!status && status.map(s => <p key={s.service}>{s.deployed}</p>)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.