首页 > 解决方案 > 无法读取未定义的属性段

问题描述

我正在使用 next.js 和 wordpress。我已经设置了我的 api.js。每当我尝试[slug]从另一个组件访问时,它都会显示 - Typerror: Cannot read property 'slug' of undefined

假设,Test如果我尝试从具有下一个链接的组件访问帖子,我还有另一个页面称为

<Link href={`/articles/${node.slug}`}>
    <a><h5>{post.name}</h5></a>
</Link>

它显示了Typerror: Cannot read property 'slug' of undefined

我的代码在创建它的同一个组件中运行良好,但是每当我尝试从具有下一个链接的另一个组件访问它时;它显示了错误。

我希望它很好理解。

这是我的代码:

api.js:

const API_URL = process.env.WP_API_URL;

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' };

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query, variables })
  });

  // error handling work
  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details', query, variables);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}

export async function getAllPosts(preview) {
    const data = await fetchAPI(
      `
      query AllPosts {
        posts(first: 20, where: {orderby: {field: DATE, order: DESC}}) {
          edges {
            node {
              id
              date
              title
              slug
            }
          }
        }
      }
      `
    );
  
    return data?.posts;
}

export async function getAllPostsWithSlug() {
    const data = await fetchAPI(
      `
      {
        posts(first: 10000) {
          edges {
            node {
              slug
            }
          }
        }
      }
    `);
    return data?.posts;
};

export async function getPost(slug) {
    const data = await fetchAPI(
      `
      fragment PostFields on Post {
        title
        excerpt
        slug
        date
        featuredImage {
          node {
            sourceUrl
          }
        }
      }
      query PostBySlug($id: ID!, $idType: PostIdType!) {
        post(id: $id, idType: $idType) {
          ...PostFields
          content
        }
      }
    `,
      {
        variables: {
          id: slug,
          idType: 'SLUG'
        }
      }
    );
  
    return data;
};

[蛞蝓].js:


<article>
   <h1>{postData.title}</h1>
       <div dangerouslySetInnerHTML={{ __html: postData.content }} />
</article>

export async function getStaticPaths() {
    const allPosts = await getAllPostsWithSlug();

    return {
        paths: allPosts.edges.map(({ node }) => `/articles/${node.slug}`) || [],
        fallback: true
    };
}

export async function getStaticProps({ params }) {
    const data = await getPost(params.slug);

    return {
        props: {
            postData: data.post
        }
    };
}

GraphQL 查询

query AllProfiles {
  businessProfiles(where: {orderby: {field: AUTHOR, order: ASC}}) {
    edges {
      node {
        date
        title
        slug
        link
        uri
   }
}

注意:由于 stackoverflow 验证,我缩短了代码。现在,问题是每当我尝试从另一个组件访问路径时,它都会显示我上面提到的错误。

我正在使用 Next 链接进行路由和所有操作。

无论如何要修复它?请指导我。

谢谢你们。

标签: javascriptreactjsecmascript-6next.js

解决方案


使用上面的 graphql 查询

query AllProfiles {
  businessProfiles(where: {orderby: {field: AUTHOR, order: ASC}}) {
    edges {
      node {
        date
        title
        slug
        link
        uri
      }
    }
  }
}

假设您将该查询定位为 slugLink并且您的函数如下所示

export async function getAllProfiles() {
    const data = await fetchAPI(`
query AllProfiles {
  businessProfiles(where: {orderby: {field: AUTHOR, order: ASC}}) {
    edges {
      node {
        date
        title
        slug
        link
        uri
      }
    }
  }
}
`);
  
 return data?.posts;
}

然后,您需要隔离 slug。如何?制作一个独立的 getProfileSlug 组件。

import { getAllProfiles } from '@lib/api';
import Link from 'next/link';

const resolveProfileSlugs = async ({ ...props }) => {
    const data = await getAllProfiles();
    return data !== null &&
        data.posts !== null &&
        data.posts.edges !== null &&
        data.posts.edges.length > 0 ? (
        data.posts.edges.map(slugs => {
            return slugs !== null &&
                slugs.node !== null &&
                slugs.node.slug !== null &&
                slugs.node.title !== null ? (
                <>
                    <Link href={`/articles/${slugs.node.slug}`} passHref key={slugs.node.id}>
                        <a {...props}>
                            {slugs.node.title}
                        </a>
                    </Link>
                </>
            ) : (
                <div>{'Slug or Title Null'}</div>
            )
        })
    ) : (
        <div>
            {
                'data from getAllProfiles either null, undefined, and/or has an edges.length = 0'
            }
        </div>
    );
};

export default resolveProfileSlugs;

我对所有 wpgraphql 项目都使用 next/typescript。随意戳我最近的回购——https: //github.com/DopamineDriven/drisdell-consulting-services


推荐阅读