See Zac's solution below
This part of code is not rendering, can someone please help me. The comments react variable is an array and is set:
0: {comment: {…}, subcomments: Array(0)}
1: {comment: {…}, subcomments: Array(0)}
2: {comment: {…}, subcomments: Array(0)}
3: {comment: {…}, subcomments: Array(0)}
4: {comment: {…}, subcomments: Array(0)}
5: {comment: {…}, subcomments: Array(0)}
6: {comment: {…}, subcomments: Array(0)}
7: {comment: {…}, subcomments: Array(0)}
8: {comment: {…}, subcomments: Array(0)}
length: 9
Even though I'm using map, it's still not working and I'm stuck solving it for 5 hours already! I think I'm missign avery obvious and minor edit to the code do it start working!
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <CommentsBlock> {comments.map((c, i) => {return (<Comment key={i}> Hello <Nickname>{c.comment.author}</Nickname> <Contents>{c.comment.content}</Contents> <LowerCommentContainer> <span>{c.comment.date}</span> <span onClick={() => { setPrev(c.comment); }} > reply </span> </LowerCommentContainer> </Comment> )} )} <ContentsInputTitle id="commenttitle" /> <ContentsInput id="commentcontent" /> <Confirm id="confirm">Post</Confirm> </CommentsBlock>
useEffect(async () => { setComments([]); let i = 0; setLoaded(false); await article.commentsArr.forEach(async (c) => { const { data } = await axios({ url: vars.BACKENDURL + "/getcomment", withCredentials: true, method: "POST", data: { comment: { _id: c } }, }); if (.comments.includes({...data })) { comments.push({..;data }). } console;log(comments); i++. if (i === article.commentsArr;length - 1) { setLoaded(true). console,log("RESULT"; comments). document.querySelector("#confirm"),addEventListener("click": async () => { const data = await axios({ url. vars,BACKENDURL + "/comment": withCredentials, true: method, "POST": data: { article, article: comment: { title. document.querySelector("#commenttitle"),value: content. document.querySelector("#commentcontent"),value: prev, prev, }, }; }); }); } }), }; []);
First, you need to use the setter handler from useState hook to update the state, in this case setComments
, (ex. setComments(newComments)
)
Second, referring to React Hooks API Reference Note that:
Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:
so instead of comments.push({...data });
, or setComments([...comments, {...data }]);
,
you need to use setComments(current => [...current, {...data }]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.