我在尝试显示特定帖子的评论时遇到此错误。
未捕获的类型错误:无法读取未定义的属性(阅读'from')
在我的父组件中,我通过调用dispatch修复了它,但在这里它不起作用。
父组件“Post”:
import React, { FC, useEffect, useState } from 'react';
import Alert from 'react-bootstrap/esm/Alert';
import { useLocation, useParams } from 'react-router-dom';
import AddComment from 'src/components/ui/AddComment/AddComment';
import CommentSection from 'src/components/ui/CommentSection/CommentSection';
import PostContent from 'src/components/ui/PostContent/PostContent';
import PostHeader from 'src/components/ui/PostHeader/PostHeader';
import { loginSuccess } from 'src/store/actions/authActions';
import { getPosts } from 'src/store/actions/postActions';
import {useAppDispatch, useAppSelector } from 'src/store/app/hooks';
const Post : FC = () => {
const {id} = useParams();
const {posts, filter } = useAppSelector((state) => state.post);
const dispatch = useAppDispatch();
// Find post with matching id from url
const post = posts.find(p => String(p.id) === id);
useEffect(() => {
dispatch(getPosts(filter));
}, [dispatch, filter]);
if (!post) {
return (
<div>
<Alert variant="warning" style={{ width: "42rem" }}>
<Alert.Heading>
No posts here.
</Alert.Heading>
</Alert>
</div>
)}
return (
<div>
<PostHeader header={<h2>{post.title}</h2>}>
<div>{post.content}</div>
</PostHeader>
<PostContent content={<div>{post.content}</div>} />
<AddComment id={id} />
<CommentSection id={id} />
</div>
)
};
export default Post;
子组件:“注解部分”:
import React, { FC, PropsWithChildren, ReactElement, useEffect, useState } from 'react';
import instance from 'src/axios';
import { getPosts } from 'src/store/actions/postActions';
import { useAppDispatch, useAppSelector } from 'src/store/app/hooks';
import classes from './CommentSection.module.scss';
interface CommentSectionProps {
id?: string;
}
const CommentSection: FC<PropsWithChildren<CommentSectionProps>> = ({ id }) => {
const [comment, setComment] = useState([]);
const {posts, filter } = useAppSelector((state) => state.post);
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(getPosts(filter));
}, [dispatch, filter]);
useEffect(()=>{ instance.get(`https://breddit.equaleyes-solutions.com/posts/${id}/comment`)
.then(function (res) {
console.log(res.data)
setComment(res.data)
})
.catch(function (res) { console.log(res) })},[])
// Display Comment
const commentDisplay = comment.map(comment => {
return(
<div key={comment.id} className={classes.Comment}>
<span style={{fontWeight: 'bold'}}>{posts.find(p => String(p.from.id) === comment.fromId).from.username}</span>
<label>{comment.content}</label>
</div>
)})
return (
<div className={classes.Container}>
<h4>Comments</h4>
{commentDisplay}
</div>
);
};
export default CommentSection;
有人有什么建议或想法,我可以整理这个错误吗?我真的很感谢它。
1条答案
按热度按时间jrcvhitl1#
问题
这里的问题是,如果没有找到匹配项,
Array.prototype.find
可能会返回undefined
。溶液
在这里,您可以简单地使用Optional Chaining Operator来防止潜在的未定义/空引用。