reactjs - React 访问对象属性并将它们显示到屏幕上
问题描述
在我的反应应用程序中,我从这样的 api 获取一些数据:
function PlayerPage() {
interface PlayerDataType {
id: number;
handle: string;
role: string;
avatar: string;
specialAbilities: null;
stats: null;
}
const [isLoading, setIsLoading] = useState(false);
const [player, setPlayer] = useState<Array<PlayerDataType>>([]);
//Fetch all forms from database
useEffect(() => {
setIsLoading(true);
fetch('https://localhost:44326/api/Players/1')
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => setPlayer(data))
.then(() => setIsLoading(false));
}, []);
如果尚未设置播放器对象,那么我只显示页面正在加载,否则显示页面,如下所示:
if (isLoading === true && !player) {
return (
<Page>
<PageTitle>Loading...</PageTitle>
</Page>
);
} else {
return (
<Page>
在播放器加载后的返回正文中,我想显示player.handle
但是当我这样尝试时:
return (
<Page>
<PageTitle>{player.handle}</PageTitle>
</Page>
);
我得到错误:
Property 'handle' does not exist on type 'PlayerDataType[]'.ts(2339)
但是,如果您回头查看我提供的原始代码块,您可以清楚地看到属性“句柄”确实存在于类型 PlayerDataType[] 上。
这里发生了什么?为什么这不起作用?
如果有帮助,这是整个页面:
import React, { useState, useEffect } from 'react';
import { Page } from './Page';
import { PageTitle } from './PageTitle';
import { useParams } from 'react-router-dom';
function PlayerPage() {
interface PlayerDataType {
id: number;
handle: string;
role: string;
avatar: string;
specialAbilities: null;
stats: null;
}
const { id } = useParams();
const [isLoading, setIsLoading] = useState(false);
const [player, setPlayer] = useState<Array<PlayerDataType>>([]);
//Fetch all forms from database
useEffect(() => {
setIsLoading(true);
fetch('https://localhost:44326/api/Players/1')
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => setPlayer(data))
.then(() => setIsLoading(false));
}, []);
console.log(id);
console.log(player);
if (isLoading === true && !player) {
return (
<Page>
<PageTitle>Loading...</PageTitle>
</Page>
);
} else {
return (
<Page>
<PageTitle>Player Name</PageTitle>
<PageTitle>{player.handle}</PageTitle> //This not working
</Page>
);
}
}
export default PlayerPage;
解决方案
你的玩家状态是一个数组PlayerDataType
。然后,数组中不存在句柄属性...
推荐阅读
- splunk - splunk 的日志被截断
- swift - 子视图位于边界层下方 - Swift - 以编程方式
- c++ - 动态分配的二维数组问题
- reactjs - 带有 React 前端的 Spring 方法
- c# - 无效的数据表格式:第 1 列的类型必须为“日期、数字、日期时间”
- javascript - 如何在 platformBrowserDynamic 中使用 appModule?
- node.js - Mongoose:无法填充嵌套的 id 数组
- python - 我是否在机器学习模型中正确使用了 onehot 编码的特征?
- ajax - 在 Geocoder 事件中刷新 MapBox GL JS 中的自定义线串图层
- python - 将函数存储为类变量,但调用时不带 self 参数