我正在學習按照這個 Githup 教程(https://github.com/adrianhajdin/project_graphql_blog)構建我的博客,但是當我使用 [slug].js 構建我的 localhost/3000/post/react-tesing 時,它給我這個錯誤: TypeError: Cannot read properties of undefined (reading 'author') 我已經檢查了好幾次但不知道。那么我該如何解決這個問題呢?謝謝!
[slug].js
import React from 'react'
import {getPosts, getPostDetails} from '../../services';
import {PostDetail, Categories, PostWidget, Author, Comments, CommentsForm} from '../../components';
const PostDetails = ({post}) => {
return (
<div className='container mx-auto px-10 mb-8'>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
<div className='col-span-1 lg:col-span-8'>
<PostDetail post={post} />
<Author author={post.author} />
<CommentsForm slug={post.slug} />
<Comments slug={post.slug}/>
</div>
<div className='col-span-1 lg:col-span-4'>
<div className='relative lg:sticky top-8'>
<PostWidget slug={post.slug} categories={post.categories.map((category) => category.slug)}/>
<Categories />
</div>
</div>
</div>
</div>
);
};
export default PostDetails;
我的 index.js - 服務:
export const getPostDetails = async (slug) => {
const query = gql`
query GetPostDetails($slug: String!) {
post(where: {slug: $slug}) {
title
excerpt
featuredimage {
url
}
author{
name
bio
photo {
url
}
}
createdAt
slug
content {
raw
}
categories {
name
slug
}
}
}
`;
const result = await request (graphqlAPI, query, {slug});
return result.post;
};
uj5u.com熱心網友回復:
只是在帖子有值之前不要渲染相應的 HTML。
import React from 'react'
import {getPosts, getPostDetails} from '../../services';
import {PostDetail, Categories, PostWidget, Author, Comments, CommentsForm} from '../../components';
const PostDetails = ({post}) => {
return (
<div className='container mx-auto px-10 mb-8'>
{ post && <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
<div className='col-span-1 lg:col-span-8'>
<PostDetail post={post} />
<Author author={post.author} />
<CommentsForm slug={post.slug} />
<Comments slug={post.slug}/>
</div>
<div className='col-span-1 lg:col-span-4'>
<div className='relative lg:sticky top-8'>
<PostWidget slug={post.slug} categories={post.categories.map((category) => category.slug)}/>
<Categories />
</div>
</div>
</div> }
</div>
);
};
export default PostDetails;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493289.html
標籤:javascript 反应
