无法使用redux读取react中undefined的属性

chhkpiq4  于 2022-12-04  发布在  React
关注(0)|答案(1)|浏览(201)

我在尝试显示特定帖子的评论时遇到此错误。
未捕获的类型错误:无法读取未定义的属性(阅读'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;

有人有什么建议或想法,我可以整理这个错误吗?我真的很感谢它。

jrcvhitl

jrcvhitl1#

问题

这里的问题是,如果没有找到匹配项,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>
  );
});

溶液

在这里,您可以简单地使用Optional Chaining Operator来防止潜在的未定义/空引用。

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>
  );
});

相关问题