为什么我获取的以数组形式返回的数据不断收到错误“对象作为 React 子对象无效”

问题描述 投票:0回答:1

应用程序.tsx

import { useEffect, useState } from "react";
import "./App.css";
import UserInput from "./components/userInput";
import { ResultRow } from "./components/ResultRow";

// type TCachedValues = {
//   [keys: string]: object | void
// };

function App() {
  const [userInput, setUserInput] = useState("");
  const [cachedResults, setCachedResults] = useState([]);

  useEffect(() => {
    const fetchCachedResults = async () => {
      try {
        const res = await fetch(
          "https://ambeigj4hx.us.aircode.run/cachedValues"
        );
        if (!res.ok) {
          throw new Response("Non 200 HTTP Status", res);
        }
        const data = await res.json();
        setCachedResults(data)
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } catch (err: any) {
        switch (err.status) {
          case 400:
            break;
          case 401:
            break;
          case 404:
            break;
          case 500:
            break;
        }
        console.log(err);
      }
      
      return () => {};
    }

    fetchCachedResults();
    
  }, []);
  
  console.log(cachedResults) 
  console.log(typeof cachedResults)

  return (
    <>
      <div className="h-screen text-white bg-gradient-radial from-[#2e4363] via-[#1e3258] to-[#111c33]">
        <main className="mx-auto px-4 py-8 max-w-2xl">
          <h1 className="font-bold text-6xl text-center">NFL STAT TRACKER</h1>
          <div className="flex justify-center mt-8">
            <UserInput
              className=""
              value={userInput}
              onChange={(e) => setUserInput(e.target.value)}
            />
          </div>
          <div className="mt-8">
            <ResultRow results={cachedResults} userInput={userInput} />
          </div>
        </main>
      </div>
    </>
  );
}

export default App;

不确定如何显示我能够获取的数据...感觉士气低落,需要帮助和一个关于如何更优雅地处理这个问题的良好解释。获取的数据位于数组中,但当我 console.log 时,它是 typeof 的,即使将其设置为空数组的状态后,它也会作为对象读取。

该项目是一个 NFL 统计跟踪器,用于跟踪我能够获取的最新数据,以便人们更轻松地查找统计数据以构建连胜彩哈哈,我希望用户能够搜索数据中列出的任何进攻球员

https://github.com/joequint22/nfl-stats

reactjs typescript fetch-api
1个回答
0
投票

不确定您喜欢哪种数据格式,但这是选项之一:

1.在保存之前转换您收到的数据

setCachedResults(transformData(data))

const transformData = (data) => {
  const [value] = data;
  const teamNames = Object.keys(value).filter(key => !['createdAt', 'updatedAt', '_id'].includes(key));
  return teamNames?.map(name => [name, data[name]]);
}

然后在 ResultsRow 组件中将渲染更改为:

    {results.map(([teamName, data], key) => {
       return (
        <div key={key}>
            <h1>${teamName}</h1>
        </div>
       )
    })}
© www.soinside.com 2019 - 2024. All rights reserved.