javascript - 如何渲染依赖 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/>
)
)
}
解决方案
如果dateRecords
是一个数组,请将其初始化为一个数组而不是一个数字:
const [dateRecords, setDateRecords] = useState([]);
在这种情况下,当执行 API 操作时,任何试图迭代的东西都dateRecords
将简单地迭代一个空数组,什么也不显示。
推荐阅读
- javascript - 如何在 react-native-snap-carousel 中使轮播循环?
- google-apps-script - 有没有办法在谷歌应用脚本的文档中添加唯一标识符?
- android - Expo Cli - 不变违规:requireNativeComponent:在 UIManager 中找不到“RNCSafeAreaProvider”
- amazon-web-services - 如何使用 cli 在云端分发中更新 lambda@edge arn
- java - 检查方法是否使用 while 或 for 循环(Java)
- python - 如何正确提取 Keras ConvNet 权重矩阵以在 Excel 中使用?
- visual-studio-code - 从 local.settings.json 读取很热
- unit-testing - 在嵌入式目标中使用 Google 测试?
- python - sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) 没有这样的列:user.name
- javascript - 带箭头的 React-router 页面