它可以在不编写class的情况下使用state以及其他的React特性,通过自定义hook,可以复用代码逻辑
// 假设 DataSource 对象具有 getComments 方法的实现
const DataSource = {
getComments: function() {
// 在这里实现获取订阅数据的逻辑
// 假设返回一个包含评论数据的数组
return [
{ id: 1, text: "Comment 1" },
{ id: 2, text: "Comment 2" },
{ id: 3, text: "Comment 3" }
];
}
};
function useSubscription() {
const data = DataSource.getComments();
return [data];
}
function CommentList(props) {
const { data } = props;
const [subData] = useSubscription();
// 在这里使用 subData 和其他逻辑进行渲染
return (
<div>
<div>{data}</div>
{/* 渲染评论列表 */}
{subData.map(comment => (
<div key={comment.id}>{comment.text}</div>
))}
</div>
);
}
// 使用 CommentList 组件
<CommentList data="hello" />;
优点:hook解决了hoc的prop覆盖问题,同时解决了render props的嵌套地狱问题,使用直观,能在return之外使用数据
注意:只能在组件顶层使用,不能在分支语句中使用