![](/img/trans.png)
[英]React Hooks (Rendering Arrays) - Parent component holding a reference of children that are mapped vs Parent component holding the state of children
[英]React hooks: Dynamically mapped component children and state independent from parent
我正在通过 API 调用从后端收集帖子(称为latestFeed
)。 这些帖子都映射到组件并有评论。 评论需要相互独立地打开和关闭。 我通过为每个评论分配一个名为showComment
的状态来管理这个机制。 showComment
根据 Hook 规则的规定在父级生成。
这是父组件。
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
一起showComment
。 在latestFeed
在useEffect
钩子中返回一个posts 数组后,它被传递到这里的子节目:
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
,所有帖子都会打开所有评论。 我希望它们只是被点击的评论。
谢谢!
您正在尝试使用单个状态,您声称您需要多个独立状态。 在需要的地方直接定义状态。
为此,请删除
const [showComment, setShowComment] = useState(false);
const handleComment = () => {
showComment ? setShowComment(false) : setShowComment(true);
};
从Parent
,从Child
和RenderText
删除showComment
和handleComment
道具,然后添加
const [showComment, handleComment] = useReducer(state => !state, false);
到RenderText
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.