我在呈现评论组件时遇到了麻烦。
所以我有一个listcomment
组件,它有两个子组件commentitem
和commentgroup
。
我的commentgroup
组件就像是一个下拉列表,您可以在其中打开和关闭它。
我尝试使用react.memo(),但它仍然呈现已经呈现的子级
我的问题是,每次我添加一个新注释时,它都会再次呈现已经呈现的子组件。 因此,已经打开commentgroup
的注释将关闭。 我使用redux
进行状态管理。
很抱歉我的英语不好。
注释数据
[{
body: "comment 1",
comment_counter: 0,
createdAt: "2020-06-14T13:42:38.465Z",
heart_counter: 0,
ownerId: "5edce08cabc7ab1860c7bdf4",
postId: "5ee3770495bfce029842bc68",
_id: "5ee6294eb7295a1c04b62374"
}, {
body: "comment 2",
comment_counter: 0,
createdAt: "2020-06-14T13:42:38.465Z",
heart_counter: 0,
ownerId: "5edce08cabc7ab1860c7bdf4",
postId: "5ee3770495bfce029842bc68",
_id: "5ee6294eb7295a1c04b62374"
}]
ListComments.js
const comments = useSelector(state => state.comment.comments)
return comments.map(comment => {
return (
<div key={comment._id}>
<CommentItem comment={comment} type="post_comment" />
<div className={classes.mLeft}>
<CommentGroup counter={comment.comment_counter} />
</div>
</div >
)
})
commentGroup.js
const CommentGroup = React.memo((props) => {
const [open, setOpen] = useState(false)
const onOpen = () => {
setOpen(true)
}
const onClose = () => {
setOpen(false)
}
return (
<div>
<Button
size="small"
color="primary"
startIcon={
!open ? <ArrowDropDownOutlinedIcon /> : <ArrowDropUpOutlinedIcon />
}
onClick={
!open ? () => onOpen() : () => onClose()
}
>
{!open ? 'View' : 'Hide'} {1} Replies
</Button>
CommentGroupOpen: {open ? 'true' : 'false'}
</div>
)
}, (prevProps, nextProps) => {
console.log(prevProps) // not getting called
if (prevProps.counter !== nextProps.counter) {
return false
}
return true
})
export default CommentGroup
CommentItem只是一个显示组件
这很可能是因为所有注释都有相同的comment._id,它被用作键。 我做了一个类似的例子,效果很好。 https://codesandbox.io/s/mutable-framework-stk5G