javascript - React - 列表中的每个 child 都应该有一个唯一的 "key" Prop

标签 javascript reactjs

在我的 react 组件中, 我的 UI 加载完美但有控制台错误我想修复错误说 - '列表中的每个 child 都应该有一个唯一的“关键” Prop '用于下面的代码。 指导我如何将 key 传递给 detailsContent

render() {
    const header = (
        <div className={css.deviceDetailsBody}>
            <div className="sidebar__header">
                <div className="sidebar__title">
                    <div>
                        {hostname}
                        {this._renderCloser()}
                        <div className={"sidebar__subtitle"}>
                            <div className="toolsBar">
                                <div className="toolsBarlet">
                                    <div className="toolsItemNarrow">{deviceTypeView}</div>
                                    {complianceStatusView}
                                    <div className="toolsItemNarrow">{managementIpAddress}</div>
                                    {deviceUpTime}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
    const horizontalLine = <div className="sidebar__horiz_line" />;
    const body = (
        <div className="body">
            {tabs}
            {tools}
        </div>
    );

    const detailsContent = [header, horizontalLine, body].map(
        currentComponent => currentComponent
    );

    return (
        <div>
            {sideBarShow && (
                <Sidebar {...sidebarProps}>
                    <div>{detailsContent}</div>
                </Sidebar>
            )}
        </div>
    );
}

为了更清晰,添加了标题和正文代码。

最佳答案

Each child in a list should have a unique "key" prop

如果使用组件而不是普通的 jsx 元素,只需将 key 属性添加到 currentComponent jsx。请注意,为简单起见,我只是使用 index 作为键。

const detailsContent = [header, horizontalLine, body].map(
  (CurrentComponent, index) => (<CurrentComponent key={index} />)
);

See CodeSandbox

使用元素,请引用the accepted answer .

关于javascript - React - 列表中的每个 child 都应该有一个唯一的 "key" Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58073901/

相关文章:

javascript - 根据输入更改 React-Select 选项

javascript - 动态创建一个元素并尝试将其值作为函数 onkeyup 中的参数传递

javascript - 将 Express 连接到 React webpack 项目

javascript - 单击 DIV 时如何切换 UL 列表?

javascript - 在 Internet Explorer 上粘贴事件监听器得到错误的参数

javascript - 如何让其他按钮功能在单击按钮时自动运行

css - 如何在 React 中导入 CSS 文件路径而不是整个文件

reactjs - React Jest 导致 "SyntaxError: Unexpected token ."

javascript - 如何申请:hover to an element

javascript 测试 URL 是相对的还是绝对的,而不是 mailto :