首页 > 解决方案 > 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”

  1. 这是什么原因造成的?我假设组件在渲染之前没有数据。
  2. 如何解决这个问题呢?

标签: reactjsnext.js

解决方案


只是您的数组中有一些项目为空,因此导致了该错误。我建议这样重写,这样可以避免不必要的错误

const App = ({ads}) => 
   (ads.items || []).map(item => item ? <Ad item={item} key={item.postingId} id={item.postingId}/> : null)

推荐阅读