reactjs - Next.js 编译错误,属性未定义
问题描述
所以有一个带有组件的索引页,列出广告。
const App = ({ads}) => (
{ (ads.items===undefined) ? <></> : ads.items.map(item => <Ad item={item} key={item.postingId} id={item.postingId}/>) }
)
export async function getServerSideProps(context) {
const res = await fetch(`www.apiadress.com/${queryString.stringify(context.query)}`)
const ads = await res.json()
// console.debug(ads)
console.debug(queryString.stringify(context.query))
return {
props: {ads}, // will be passed to the page component as props
}
}
和组件 Ad 接收这些道具,并呈现卡片
const Ad = props => (
<Card className="customCard">
<Card.Body>
<Card.Text className="text">
<div className="mainDetails">
<h1 className="ad_Title"><Link href="[ad]" as={props.item.postingId}>{props.item.title}</Link></h1>
<p>posted on: {props.item.postingDate.day} / {props.item.postingDate.month}
{props.item.postingDate.year} by {props.item.employer}
</p>
<div className="description">
<p><span><Cash /><b> {props.item.rateFrom}- {props.item.rateTo} per hour </b></span> <GeoAlt /> <b>{props.item.city}</b></p>
<p> <Clock /> <b>{props.item.jobType}</b></p>
</div>
<p>{props.item.description.slice(0, 230)}.....</p>
</div>
<div>
<img src={props.item.employerLogoUrl} alt={props.item.employer} className="empImg" />
<Button variant="primary" href=""> <Heart width="12" height="12"/> SHORLIST </Button>
</div>
</Card.Text>
</Card.Body>
</Card>
export default Ad;
使用 NPM 运行开发 - 一切正常,但在 NPM 运行构建时出现错误
预呈现页面“/componenets/ad/ad”时发生错误。阅读更多: https ://err.sh/next.js/prerender-error TypeError:无法读取未定义的属性“postingId”
- 这是什么原因造成的?我假设组件在渲染之前没有数据。
- 如何解决这个问题呢?
解决方案
只是您的数组中有一些项目为空,因此导致了该错误。我建议这样重写,这样可以避免不必要的错误
const App = ({ads}) =>
(ads.items || []).map(item => item ? <Ad item={item} key={item.postingId} id={item.postingId}/> : null)
推荐阅读
- ios - 了解钥匙串项目的访问控制设置`.userPresence`
- php - php goutte web scraper 不时给出不同的结果
- react-native - 合并两个 useState 值的最简单方法
- amazon-web-services - 除了来自 AWS SQS 的新消息外,我可以接收所有消息吗?
- python - Pyinstaller 没有名为 pytube 的模块
- php - 如何将日期时间从默认时区 (IST) 获取到基于不同用户的时区
- scala - 词对同现
- node.js - 如何调用另一个模式(mongodb)中的模式的数据
- biopython - Biopython PDB - 寻找 RNA 链
- php - 如何在magento 2中以编程方式取消订单