簡體   English   中英

為什么反應不渲染更新 state?

[英]Why react not rendering updated state?

我的應用程序中有一個社區功能,用戶可以在其中發表評論。我想在單擊特定圖標時切換評論可見性的 state。 圖標:

 <i className="fa-solid fa-message" onClick={(e)=>handleComment(e)}></i>
        {!props.post.isCommentVisible && <> <Container maxW="md" centerContent p={8}>
          {props.post.comment.map((comm) => (
            <Text>{comm}</Text>
          ))}

切換評論可見性的 function 是:

function handleComment(e)
  {
    const id=props.post.id;
    posts.map((post)=>{
      if(post.id==id)
      {
       if(post.isCommentVisible=="false")
       {
         post.isCommentVisible="true";
       }
       else
       {
        post.isCommentVisible="false";
       }
         
         
       db.collection("posts").doc(id).set(post);
      }
    })

  }

有趣的是,評論可見性的 state 已更新,但 React 並未重新呈現已更改的 state。

無論props.post.isCommentVisible"true"還是"false" ,表達式.props.post.isCommentVisible將始終為false ,因為"anyString"始終為 true。

假設您在某處定義:

const [posts, setPosts] = useState([]);

然后通過一些獲取操作更新填充的posts ,你必須像這樣調用setPosts

setPosts(
    posts.map((x) => ({
        ...x,
        isCommentVisible:
            x.id === post.id ? !x.isCommentVisible : x.isCommentVisible,
    }))
);

(使用任何你想達到結果的方法,介意 Rocky Sims 的評論)

這將導致重新渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM