提问人:bi3ri 提问时间:11/17/2023 最后编辑:Drew Reesebi3ri 更新时间:11/17/2023 访问量:41
分配唯一键时钩子的动态数量合法吗?
Dynamic number of hooks legit when assigning unique key?
问:
我需要在 react 代码中呈现动态用户生成的 markdown 内容。Markdown 内容发生了变化,生成的 react 代码应该是响应式的,需要钩子来做到这一点。我的第一个解决方案创建了已知错误“渲染之间的钩子数量不同”,但是如果我为每个用户内容给 markdown 组件一个唯一的键,一切正常,没有问题。在此示例中,将呈现视频播放器或地图视图,每个播放器或地图视图都有自己的挂钩。
问题我的解决方案合法吗?
function Markdown(userContent) {
// parse userContent
return <Some react code based on userContent including hooks />;
}
function App() {
const [content, setContent] = useState("some markdown text ::render-video-player::");
const someUniqueKey = useGiveMeUniqueKey();
const otherUserContent = "some other markdown text ::render-map-view::";
return (
<>
<Markdown key={someUniqueKey} userContent={content} />
<Pressable onPress={() => setContent(otherUserContent)}>
<Text>Click me!</Text>
</Pressable>
</>
);
}
重要的部分是,如果没有我得到上面提到的不同数量的钩子错误。key={someUniqueKey}
这是一些晦涩难懂的解决方案,会在路上造成麻烦,还是合法的?
答: 暂无答案
评论