【问题标题】:Next Js TypeError: Cannot read property 'xxx' of undefinedNext Js TypeError:无法读取未定义的属性“xxx”
【发布时间】:2019-07-28 15:22:28
【问题描述】:

运行“下一次导出”时出现以下错误。我的构建很好,但导出失败。我一直在关注很多教程,但找不到解决方案。我是否正确定义了我的someEntryAsProp

import Layout from '../components/myLayout.js'
import Link from 'next/link'
import {createClient} from '../helpers/getcontent';
import { type } from 'os';


function getPosts(){
  return [
    { id:'hello-nextjs' , title:'Hello Next.js' },
    { id:'learn-nextjs' , title:'Learn Next.js is awesome' },
    { id:'deploy-nextjs' , title:'Deploy apps with Zeit' },
  ]
}
const PostLink = ({ post }) => (
  <li>
    <Link as={`/p/${post.id}`} href={`/post?title=${post.title}`}>
      <a>{post.title}</a>
    </Link>
  </li>
)

const Index = () => (

  <Layout>
    <h1>My Blog</h1>
    <p>{someEntryAsProp.fields.title}</p>
    <ul>
    { getPosts().map((post) => (
       <PostLink key={post.id} post={post}/>
    ))}
    </ul>
  </Layout>
  );

  Index.getInitialProps = async () => {

    console.log('> Starting import',);
   const client = createClient();
     const entries = await client.getEntries({
       // some query
      content_type:type,
       include:2
     })

   console.log(entries.items[0])
     console.log('> Content gotten and written for',)

    return { someEntryAsProp: entries.items[0] };
    //return {};
  };

  export default Index  

错误:

TypeError: 无法读取未定义的属性“someEntryAsProp”

谁能帮我看看我哪里做错了?

【问题讨论】:

  • 难道你还必须使用this.props.someEntryAsProp 吗?
  • 我尝试使用它,但没有运气。添加 .

    {this.props.someEntryAsProp.fields.title}

    给出另一个错误 *TypeError: Cannot read property 'props' of undefined *

标签: javascript ecmascript-6 es6-promise next.js contentful


【解决方案1】:

您需要将道具作为参数传递给您的页面组件:

const Index = ({someEntryAsProp}) => (...)

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 2019-11-15
    • 2021-11-02
    • 2022-11-17
    • 2023-01-31
    • 2012-12-04
    • 2020-12-24
    • 2018-03-15
    • 2016-03-25
    相关资源
    最近更新 更多