You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript渲染玩家数据时提示handle属性不存在TS2339错误排查

问题原因

你的TypeScript报错是两个逻辑不匹配导致的:

  • 你给player state定义的类型是PlayerDataType[](玩家数据数组),数组类型本身不存在handle属性,只有数组内的单个PlayerDataType类型对象才有该属性
  • 你调用的接口/api/Players/1是查询单条玩家数据,返回的是单个对象而非数组,你给数组类型的state赋值单个对象本身就存在类型不匹配
修复方案

1. 修改state的类型定义

将player state的类型从数组改为单个玩家对象,初始值设为null:

// 原来的错误写法
// const [player, setPlayer] = useState<Array<PlayerDataType>>([]);
// 修正后的写法
const [player, setPlayer] = useState<PlayerDataType | null>(null);

2. 修正加载判断逻辑

原判断逻辑存在漏洞,isLoading为false但player还未赋值时,会直接进入渲染逻辑访问不存在的属性,修改判断条件:

// 原来的错误写法
// if (isLoading === true && !player)
// 修正后的写法:只要还在加载中/玩家数据未赋值,就显示加载态
if (isLoading || !player) {
  return (
    <Page>
      <PageTitle>Loading...</PageTitle>
    </Page>
  );
}

修改完后你就可以正常访问player.handle属性,因为此时TS可以确定进入渲染分支时player一定是已赋值的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<PlayerDataType | null>(null);

  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 || !player) {
    return (
      <Page>
        <PageTitle>Loading...</PageTitle>
      </Page>
    );
  } else {
    return (
      <Page>
        <PageTitle>Player Name</PageTitle>
        <PageTitle>{player.handle}</PageTitle>
      </Page>
    );
  }
}

export default PlayerPage;

内容的提问来源于stack exchange,提问作者GrillOwner69420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:51:02