首页 > 解决方案 > 如何渲染依赖 API 数据的 React 组件?

问题描述

我正在尝试在依赖于外部 API 数据的组件文件中呈现组件。基本上,我在我的组件中的返回使用了一个正在等待数据的组件,但是我得到一个错误 dataRecords is undefined 因此无法映射。

希望我的代码能更好地解释这一点:

// Component.js

export const History = () => {

const [dateRecords, setDateRecords] = useState(0)
const { data, loading } = useGetRecords() // A custom hook to get the data

useEffect(() => {
  fetchData()
}, [loading, data])

const fetchData = async () => {
  try {
    let records = await data
    setDateRecords(records)
  } catch (err) {
    console.error(err)
  }
}

// Below: Render component to be used in the component return
const GameItem = ({ game }) => {
  return <div>{game.name}</div>
}

// When I map over dateRecords, I get an error that it is undefined
const renderRecords = async (GameItem) => {
  return await dateRecords.map((game, index) => (
    <GameItem key={index} game={game} />
  ))
}

const GameTable = () => {
  return <div>{renderRecords(<GameItem />)}</div>
}



return(
  // Don't display anything until dateRecords is loaded
  {dateRecords? (
    // Only display <GameTable/> if the dateRecords is not empty
    {dateRecords.length > 0 && <GameTable/>
  )
)
}

标签: javascriptreactjsasynchronousasync-await

解决方案


如果dateRecords是一个数组,请将其初始化为一个数组而不是一个数字:

const [dateRecords, setDateRecords] = useState([]);

在这种情况下,当执行 API 操作时,任何试图迭代的东西都dateRecords将简单地迭代一个空数组,什么也不显示。


推荐阅读