在React/Material UI中使用map填充select时出现问题



我正在尝试用国家列表填充Material的UI,如下所示:

import React from "react";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import countries from "./data";
const simpleCountrySelect = props => {
return (
<>
<FormControl>
<InputLabel id="countrySelectLabel">Country</InputLabel>
<Select labelId="countrySelectLabel" id="countrySelect" value=''>
{countries.map((code, name, index) => (
<MenuItem key={index} value={code}>
{name}
</MenuItem>
))}
</Select>
</FormControl>
</>
);
};
export default simpleCountrySelect;

为简洁起见,不受控制的组件。但我得到了以下错误:

Encountered two children with the same key, `.$.$.$[object Object]`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

以下是data.js文件的示例:

export default [
{ code: "AD", name: "Andorra" },
{ code: "AE", name: "United Arab Emirates" },
{ code: "AF", name: "Afghanistan" },
{ code: "AG", name: "Antigua and Barbuda" }
];

我在这里做错了什么?

编辑:将keycode更改为index,仍然没有任何内容。

实际上是map方法使用错误。

传递到map中函数的参数依次为itemindexarray。在您的情况下,countries.map((code, name, index) => {...})code表示数据数组中的单个项,例如{code: "AD", name: "Andorra"}name表示数据数组的索引,index表示数据数组本身。你得到相同的键错误是因为它们是相同的值-数据数组。

因此,在您的目的中编写映射函数的正确方法应该如下:

countries.map(({ code, name }, index) => (
<MenuItem key={index} value={code}>
{name}
</MenuItem>
))

整个文件应如下所示:

import React from "react";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import countries from "./data";
const simpleCountrySelect = props => {
return (
<>
<FormControl>
<InputLabel id="countrySelectLabel">Country</InputLabel>
<Select labelId="countrySelectLabel" id="countrySelect" value=''>
{countries.map(({code, name}, index) => (
<MenuItem key={index} value={code}>
{name}
</MenuItem>
))}
</Select>
</FormControl>
</>
);
};
export default simpleCountrySelect;

似乎您打算销毁数组中的每个对象,但您错过了大括号:

countries.map(({code, name}) =>

遇到两个有相同键的孩子是一个警告,说明您的两个菜单项有相同的键,因为您使用的是国家代码作为键,这也可能是真的。我建议将数组的索引用作键。其次,你必须在地图中返回。所以它应该是类似的东西

countries.map((index, code, name) => {
return(
<Menu.Item key={index} value={code}>
{name}
</Menu.Item>
)})

试试这个,应该很好。

最新更新