我正在處理 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>
))}
);
}
當您嘗試使用props.gyms
您的useState
默認值,你傳遞一個對象(道具對象:{ gyms: [...] }
)而不是健身房陣列。
它可以通過傳遞props.gyms
給useState
:來解決useState(props.gyms)
,或者props.gyms
直接在你的組件中使用 render: 來解決{props.gyms.map(...)}
。
在這種情況下,您不需要狀態。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句