我試圖在依賴于來自外部 API 的資料的組件檔案中呈現一個組件。基本上,我在組件中的回傳使用了一個正在等待資料的組件,但是我收到 dataRecords 未定義的錯誤,因此無法映射。
希望我的代碼能更好地解釋這一點:
// 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/>
)
)
}
uj5u.com熱心網友回復:
如果dateRecords
是陣列,則將其初始化為陣列而不是數字:
const [dateRecords, setDateRecords] = useState([]);
在這種情況下,當 API 操作正在執行時,任何嘗試迭代的內容dateRecords
都將簡單地迭代一個空陣列,不顯示任何內容。
uj5u.com熱心網友回復:
您已將 dateRecords 的初始狀態設定為 0,這是一個數字且不可迭代。您應該將初始狀態設定為空陣列:
const [dateRecords, setDateRecords] = useState([]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318801.html
標籤:javascript 反应 异步 异步等待