javascript - 在 react 关键 Prop 被剥离

标签 javascript reactjs

我正在生成一个 TSX 元素列表:

    this.productsModel = this.state.products.map(o => (
            <Grid.Column key>

但是,react 警告我:

Warning: Each child in a list should have a unique "key" prop.



因此,在推荐的做法 [1] 中,我补充说:
    this.productsModel = this.state.products.map((o, i) => (
            <Grid.Column key={i}>

但是key={i}无论元素是什么( Grid.Columndiv 等),都会在渲染时被去除。
怎么会?如何解决这个问题?

[1] https://reactjs.org/docs/lists-and-keys.html#keys

最佳答案

key 元素不应该传递给 DOM,它是仅用于 React 优化的保留 Prop

所以当你添加键时

  this.productsModel = this.state.products.map((o, i) => (
        <Grid.Column key={i}>

键甚至没有传递给 Grid.Column 组件,而是在实际传递所有 Prop 时被 read 剥离

您还需要为从 map 函数中返回的元素提供唯一键

Key is provided for react to keep track of elements being rendered, so that if an element is deleted or the list is sorted, it need not re-mount everything but compares the correct elements during its virtual DOM comparison. In this way it actually improves performance



即使删除了警告,使用索引键也不会提供太多好处。最好使用产品数组中每个产品对象的唯一 ID 作为键

关于javascript - 在 react 关键 Prop 被剥离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61751301/

相关文章:

javascript - $( "#tabs").tabs();不是函数

javascript - React 在按钮单击时动态添加 n 个 div 到页面

reactjs - 为什么我的 context.router 在我的 React 组件中未定义?

javascript - react map 函数: how to output content of all nested arrays at once?

javascript - 将 Quill 导入 React 应用程序会抛出 "React is not defined"、 "Unexpected token import"

javascript - 模拟从 <asp :button> 上的 <button> 单击

javascript - 如何仅通过 HTML 调用函数内部的函数

javascript - 使用 JS 将 Base64 转为 PNG

reactjs - 在 React 中动态渲染另一个组件内的组件

c# - Asp.Net Core SPA 与分离解决方案(Asp.Net Core WebApi + Web 应用程序)