gpt4 book ai didi

javascript - 我们必须为哪些地方和哪些元素提供唯一 key ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:25 28 4
gpt4 key购买 nike

我一直认为唯一需要唯一键的地方是在 listsarrays 中,比如 map,但今天我写了一个为我的组件加载屏幕,以便向用户显示加载,并且在加载结束后我执行 setState 并让渲染器知道是时候渲染真实 View 了。
但是我看到新组件没有被渲染并且加载仍然在屏幕上!经过大量测试后,我看到一切正常,最后我想给它一把 key ,也许会发生什么事!!它做到了!,问题解决了,我很困惑为什么那里需要一把 key
所以这是我所做的和发生的事情的 sudo 代码:

render () {
//with no key, this doesn't render properly
const finalView = this.state.isLoading ?
<UIManager key={1} json= {myLoadingComponentJSON} />
:
<UIManager key={2} json={myFormJson} />;

return () {
finalView
}
}

我可以挑衅地看到这里的问题可能是我正在使用一个名为 UIManager 的组件并且我使用一个 JSON 来知道这个组件应该呈现什么样的元素,并且可能两个 UIManager 都有相同的 key ?好吧,我不确定,但我仍然认为这里不需要 key 。

最佳答案

Which places and for what elements do we have to provide a unique key?

只为您希望项目重新排序的 sibling 提供一个(想想列表项)。

如果 child 是唯一的(即没有 sibling ),则不需要key

key 在具有相同祖先的 sibling 中应该是唯一的。

因此对于 UIManager 的情况,您可以提供一个名称作为键。

const finalView = this.state.isLoading ? 
<UIManager key={'LoadingComp'} json= {myLoadingComponentJSON} />
:
<UIManager key={'Form'} json={myFormJson} />;

为什么?

真正的原因是 React 如何做 Reconciliation .如果没有 key,React 只会看到 json 属性并检查它是否发生了变化(深度嵌套的 JSON 数据可能会出现性能问题 - 慢速/掉帧)。如果它发现 json 有任何变化,它将销毁之前的 UIManager 实例。

参见 Tradeoffs due to heuristics .

总结:

通过提供 key,React 可以更轻松地检查差异。

关于javascript - 我们必须为哪些地方和哪些元素提供唯一 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753627/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com