首页 > 解决方案 > 这是从哪里来的:警告:列表中的每个孩子都应该有一个唯一的“关键”道具

问题描述

我尝试了这个CodeSandbox并在本地的 VCode 中尝试了它,但在日志中看不到这个警告来自哪里:

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

Check the render method of `App`. See https://reactjs.org/link/warning-keys for more information.
    at CurrentForm (http://localhost:3000/static/js/main.chunk.js:1284:11)
    at App (http://localhost:3000/static/js/main.chunk.js:1102:70)

我更改了CurrentForm组件“Form.js” map,所以它key有一个使用“npm i uuid”之类的唯一 ID,但事实并非如此。

标签: reactjsdictionarywarningsunique-key

解决方案


Form向组件添加密钥: Codesandbox

import React, { useReducer } from "react";
import ReactDOM from "react-dom";
import { Router } from "@reach/router";
import { Form, Result, Landing } from "./steps";
import { NavigationButtons } from "./components";
import { initialState, dataReducer, DataContext } from "./dataContext";
import { formConfig } from "./consts/formConfig";

import "./styles.css";

function App() {
  return (
    <div>
      <DataContext.Provider value={useReducer(dataReducer, initialState)}>
        <Router>
          <Landing path="/" />
          {formConfig.map(({ prevStep, ...props }, index) => (
            <Form
              key={index}
              {...props}
              render={(prevStep) => <NavigationButtons prevStep={prevStep} />}
            />
          ))}
          <Result path="result" />
        </Router>
      </DataContext.Provider>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

推荐阅读