我正在latestFeed通過 API 呼叫從后端收集帖子(稱為)。這些帖子都映射到組件并有評論。評論需要相互獨立地打開和關閉。我通過showComment為每個評論分配一個狀態來管理這個機制。showComment根據 Hooks 規則的規定,在父級生成。
這是父組件。
import React, { useState, useEffect } from "react";
import { getLatestFeed } from "../services/axios";
import Child from "./Child";
const Parent= () => {
const [latestFeed, setLatestFeed] = useState("loading");
const [showComment, setShowComment] = useState(false);
useEffect(async () => {
const newLatestFeed = await getLatestFeed(page);
setLatestFeed(newLatestFeed);
}, []);
const handleComment = () => {
showComment ? setShowComment(false) : setShowComment(true);
};
return (
<div className="dashboardWrapper">
<Child posts={latestFeed} showComment={showComment} handleComment={handleComment} />
</div>
);
};
export default Parent;
latestFeed與 一起構建showComment。在鉤子中latestFeed回傳一組帖子后useEffect,它被傳遞給這里的子節目:
import React, { useState } from "react";
const RenderText = ({ post, showComment, handleComment }) => {
return (
<div key={post._id} className="postWrapper">
<p>{post.title}</p>
<p>{post.body}</p>
<Comments id={post._id} showComment={showComment} handleComment={() => handleComment(post)} />
</div>
);
};
const Child = ({ posts, showComment, handleComment }) => {
return (
<div>
{posts.map((post) => {
<RenderPosts posts={posts} showComment={showComment} handleComment={handleComment} />;
})}
</div>
);
};
export default Child;
但是,每當我觸發時handleComments,所有帖子的所有評論都會打開。我希望它們只是被點擊的評論。
謝謝!
uj5u.com熱心網友回復:
您正在嘗試使用單個狀態,您聲稱您需要多個獨立狀態。在需要的地方直接定義狀態。
為此,請洗掉
const [showComment, setShowComment] = useState(false);
const handleComment = () => {
showComment ? setShowComment(false) : setShowComment(true);
};
from Parent,從and 中洗掉showComment和handleComment道具,然后添加ChildRenderText
const [showComment, handleComment] = useReducer(state => !state, false);
到RenderText。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/358226.html
標籤:javascript 反应 反应钩子
上一篇:重構類以在React中運行組件
