开发者问题收集

在 React 组件中无法读取未定义的属性,但在 getStaticProps 函数中可以正常工作

2022-10-04
437

我正在尝试使用 Node.js、React 和 graphql 创建一个博客。我对所有这些技术(包括 Java/Typescript 本身)都不熟悉。非常感谢您的帮助。 目前,我无法获取要显示的文章数据。 在函数 getStaticProps 中,我可以正常读取 graphql 响应的数据。 但是当我将该数据作为参数传递给 React 组件时(因为 getStaticProps 在构建时提供该数据),我无法再访问该数据并收到错误消息“TypeError:无法读取未定义的属性(读取‘文章’)”。

以下是我的代码:

import {GetStaticProps} from "next";
import {serverSideTranslations} from "next-i18next/serverSideTranslations";
import {ssrGetBlog} from "../../generated/page";

// @ts-ignore implicitly has any type
export default function Index(data) {
    console.log(data.attributes) //TypeError: Cannot read properties of undefined (reading 'articles')
                                 // below in getStaticProps this worked!?

    return (
        <div className="relative bg-gray-50 px-4 pt-16 pb-20 sm:px-6 lg:px-8 lg:pt-24 lg:pb-28">
            <div className="absolute inset-0">
                <div className="h-1/3 bg-white sm:h-2/3"/>
            </div>
            <div className="relative mx-auto max-w-7xl">
                <div className="text-center">
                    <h2 className="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
                        {data.blogHeading}
                    </h2>
                    <p className="mx-auto mt-3 max-w-2xl text-xl text-gray-500 sm:mt-4">
                        {data.blogDescription}
                    </p>
                </div>
                <div className="mx-auto mt-12 grid max-w-lg gap-5 lg:max-w-none lg:grid-cols-3">
                    {data.attributes.articles.data.map((article) => (
                        <div
                            key={article.attributes.title}
                            className="flex flex-col overflow-hidden rounded-lg shadow-lg"
                        >
                            <div className="flex-shrink-0">
                                <img
                                    className="h-48 w-full object-cover"
                                    src={article.attributes.articleImg.data.attributes.url}
                                    alt=""
                                />
                            </div>
                            <div className="flex flex-1 flex-col justify-between bg-white p-6">
                                <div className="flex-1">
                                    <p className="text-sm font-medium text-indigo-600">
                                        <a href={"not implemented: article.attributes.articleCategory.data.attributes.slug"} className="hover:underline">
                                            {"none existent: article.attributes.articleCategory.data.attributes.categoryName"}
                                        </a>
                                    </p>
                                    <a href={article.attributes.slug} className="mt-2 block">
                                        <p className="text-xl font-semibold text-gray-900">
                                            {article.attributes.title}
                                        </p>
                                        <p className="mt-3 text-base text-gray-500">
                                            {article.attributes.shortDescription}
                                        </p>
                                    </a>
                                </div>
                                <div className="mt-6 flex items-center">
                                    <div className="flex-shrink-0">
                                        <a href={"not implemented: article.attributes.author.href"}>
                                            <span className="sr-only">{"not implemented: article.author.authorName"}</span>
                                            <img
                                                className="h-10 w-10 rounded-full"
                                                src={"not implemented: article.attributes.author.authorImg"}
                                                alt=""
                                            />
                                        </a>
                                    </div>
                                    <div className="ml-3">
                                        <p className="text-sm font-medium text-gray-900">
                                            <a href={"not implemented: article.attributes.author.authorUrl"} className="hover:underline">
                                                {"not implemented: article.attributes.author.name"}
                                            </a>
                                        </p>
                                        <div className="flex space-x-1 text-sm text-gray-500">
                                            <time dateTime={article.attributes.publishedOn}>{article.attributes.publishedOn}</time>
                                            <span aria-hidden="true">&middot;</span>
                                            <span>{"not implemented: article.attributes.readingTime"} read</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
}

export const getStaticProps: GetStaticProps = async (context) => {
    const {locale} = context;

    // @ts-ignore
    const blogQuery = await ssrGetBlog.getServerPage({}, context);
    const data = blogQuery.props.data?.blog?.data; //props.data?.blog?.data?.attributes;
    //console.log(data);  // works fine
    //console.log(data.attributes.articles.data[0]); // works fine
    return {
        props: {
            data,
            ...(await serverSideTranslations(locale || "", ["common"])),
        },
    };
};
2个回答

尝试一下,也许你没有正确访问组件的 props

export default function Index(props) {
    console.log(props.data.attributes)
}

export default function Index({ data }) {
    console.log(data.attributes)
}
Sovari
2022-10-04
export const getStaticProps: GetStaticProps = async (context) => {
const {locale} = context;

// @ts-ignore
const blogQuery = await ssrGetBlog.getServerPage({}, context);
const data = blogQuery.props.data?.blog?.data; //props.data?.blog?.data?.attributes;
//console.log(data);  // works fine
//console.log(data.attributes.articles.data[0]); // works fine

const comething = await serverSideTranslations(locale || "", ["common"])
return {
    props: {
        data,
        ...comething,
    },
};

};

也许可以试试这个?

Bilal Haider
2022-10-04