我目前正在完成一個前端導師挑戰,其中涉及構建一個互動式評論部分。在這個專案中,我希望用戶能夠不斷地相互回復,因此我使用了遞回組件。
我將粘貼兩個違規組件的代碼
這是我的評論組件代碼
// Comment.jsx
import { useEffect } from "react";
import ReplySection from "./ReplySection";
const Comment =({content, upvotes,image,username, isUser, replies, replyMethod, createdAt, id,upvoteMethod})=> {
useEffect(()=> {
console.log(replies)
})
return(
<div className="comment-container" key = {id}>
<div className="comment">
<div className="upvotes-section">
<div className="upvotes">
<img id="upvote" src="/images/icon-plus.svg" onClick={()=> {
upvoteMethod(id, "upvote")
}}></img>
<h3>{upvotes}</h3>
<img id="downvote" src="/images/icon-minus.svg" onClick={()=> {
upvoteMethod(id, "downvote")
}}></img>
</div>
</div>
<div className="comment-side">
<div className="comment-header">
<div className="profile">
<img src={image}></img>
<h5>{username}</h5>
<h6 className="created-at">{createdAt}</h6>
</div>
<div className="options">
<img src={isUser ? "images/icon-delete.svg" : ""}></img>
<img src="/images/icon-reply.svg" onClick={()=> {
replyMethod(id)
}}></img>
</div>
</div>
<div className="comment-content">
<h5>{content}</h5>
</div>
</div>
</div>
<ReplySection reply={replies} replyMethod={replyMethod} upvoteMethod={upvoteMethod}></ReplySection>
</div>
)
}
export default Comment;
這是回復部分,其中存盤了每個評論的所有回復。
import { useEffect } from "react";
import Comment from "./Comment";
const ReplySection=({reply,replyMethod,upvoteMethod})=> {
return(
<div className="reply-section">
{reply.map(el=> {
return(
<Comment content = {el.content} upvotes={el.score} id={el.id} upvoteMethod = {upvoteMethod} image = {el.user.image.png} username = {el.user.username} replyMethod = {replyMethod} replies = {el.replies} createdAt={el.createdAt} isUser={ el.user.username === "juliusomo"? true :false} key={el.id}></Comment>
)
})}
</div>
)
}
export default ReplySection;
這是我的 App jsx 檔案,我傳遞的物件和方法都位于其中。
import Comment from './components/Comment';
import './App.css';
import CommentArea from './components/CommentArea';
import TextField from './components/TextField';
import { useState } from 'react';
function App() {
let date = new Date()
let displayedComments = [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "./images/avatars/image-amyrobson.png",
"webp": "./images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "./images/avatars/image-maxblagun.png",
"webp": "./images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "./images/avatars/image-ramsesmiron.png",
"webp": "./images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
},
{
"id": 4,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
}
}
]
}
]
const [comments,setComment] = useState(displayedComments);
const upvotePost=(id, action)=> {
let counter = 0
action==="upvote"? counter : counter--;
if (Math.abs(counter) <= 1) {
const mult = action === "upvote" ? 1 : -1;
setComment(
comments => comments.map((comment) =>comment.id === id
? {...comment, score: comment.score (1*mult)}
: comment
)
);
}
console.log(counter)
}
const dateToMonth=(month)=> {
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
return months[month]
}
const newComment=()=> {
let comment = document.querySelector(".text-area")
if (comment.value !="") {
setComment([...comments, {"id":Math.random()*100000,
"content":comment.value,
"createdAt": `${dateToMonth(date.getMonth())}`,
"score": 0,
"user": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"replies": []}])
}
}
const newReply=(id)=> {
let commentClone = [...comments]
for (let i =0; i<commentClone.length; i ) {
if (commentClone[i].id == id) {
commentClone[i].replies.push({
"id": Math.random() * 10000,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
}
})
setComment(commentClone)
}
}
}
return (
<div className="App">
<CommentArea replyMethod = {newReply} upvoteMethod ={upvotePost} comments={comments}></CommentArea>
<TextField commentMethod={newComment}></TextField>
</div>
);
}
export default App;
當我打開實時服務器時,我最終得到了這個錯誤:
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at ReplySection (ReplySection.jsx:5:1)
at renderWithHooks (react-dom.development.js:16398:1)
at mountIndeterminateComponent (react-dom.development.js:21144:1)
at beginWork (react-dom.development.js:22634:1)
at beginWork$1 (react-dom.development.js:27597:1)
at performUnitOfWork (react-dom.development.js:26733:1)
at workLoopSync (react-dom.development.js:26642:1)
at renderRootSync (react-dom.development.js:26611:1)
at recoverFromConcurrentError (react-dom.development.js:26020:1)
at performSyncWorkOnRoot (react-dom.development.js:26264:1)
奇怪的是,當我在我的 Comment 組件中控制臺記錄回復陣列時,它只顯示一個陣列,沒有什么不尋常的。
我被這個問題難住了,想知道發生了什么。幫助將不勝感激。
uj5u.com熱心網友回復:
導致這種情況的情況是......
第一次使用Comment將replies狀態初始化為undefined。它可能會在稍后在效果掛鉤中更新,但在此之前,您不能呼叫map()它。
簡單的解決方案是將陣列狀態初始化為陣列
const [replies, setReplies] = useState([]); // empty array
您的一些嵌套回復沒有replies屬性,即el.replies未定義。
在這些情況下,您可以使用可選鏈接來安全地呼叫.map()...
{reply?.map((el) => (
<Comment
content={el.content}
... etc
/>
))}
或者如果您需要對布局進行更多控制,請使用條件渲染
{reply && (
{/* content when reply exists */}
)}
{!reply && (
{/* content when reply does not exist */}
)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470972.html
標籤:javascript 反应
上一篇:在另一個方法中使用一個方法
