首页 > 解决方案 > 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;

标签: reactjstypescript

解决方案


你的玩家状态是一个数组PlayerDataType。然后,数组中不存在句柄属性...


推荐阅读