我正在處理 next.js 專案,我正在嘗試將資料從“gymlist”頁面傳遞到“table”組件。
這是我有 getStaticProps 函式的“gymlist”頁面:
export default function Gyms({gyms}) {
return (
<Table gyms={gyms}/>
)
}
export async function getStaticProps() {
const res = await fetch(`${server}/api/gyms`)
const gyms = await res.json()
console.log(gyms);
if (!gyms) {
return {
notFound: true,
}
}
return {
props: {
gyms,
// Will be passed to the page component as props
},
};
}
console.log 正確顯示了我在資料庫中的健身房串列。
這是我收到錯誤的表組件:gyms.map is not a function
export default function Table(props) {
const [gyms, setGyms] = useState(props);
return (
{gyms?.map((gym, index) => (
<p> {gym.name} </p>
))}
);
}
uj5u.com熱心網友回復:
當您嘗試使用props.gyms您的useState默認值,你傳遞一個物件(道具物件:{ gyms: [...] })而不是健身房陣列。
它可以通過傳遞props.gyms給useState:來解決useState(props.gyms),或者props.gyms直接在你的組件中使用 render: 來解決{props.gyms.map(...)}。
在這種情況下,您不需要狀態。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370144.html
標籤:javascript 反应 下一个.js
