无法读取redux中未定义的属性



当我试图显示特定帖子的评论时,我得到这个错误。

Uncaught TypeError: Cannot read properties of undefined (reading 'from')

在我的父组件中,我通过调用调度来修复它,但在这里它不起作用。

父组件"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;
谁有任何建议或想法,我可以如何解决这个错误?我真的很感激。

Issue

这里的问题是,如果没有找到匹配,Array.prototype.find可能返回undefined

// 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} // <-- undefined
</span>
<label>{comment.content}</label>
</div>
);
});
<标题>

解决方案在这里,您可以简单地使用可选链接操作符来防止潜在的未定义/null引用。

const [comments, setComments] = useState([]);
...
useEffect(/* effect to update comments state */);
...
// Display Comment
const commentDisplay = comments.map(comment => {
const post = posts.find(p => String(p.from.id) === comment.fromId);
return (
<div key={comment.id} className={classes.Comment}> 
<span style={{fontWeight: 'bold'}}>
{post?.from.username} // <-- null/undefined check
</span>
<label>{comment.content}</label>
</div>
);
});

最新更新