我创建了一个无状态组件并传递了道具。但是,在浏览器中却出现此错误:警告:列表中的每个孩子都应该有一个唯一的“键”道具。
这是我尝试过的。
const OptionItem = (props) => {
return (
<option key={props.customerId} value={props.customerValue}>
Code: {props.customerCode} Name: {props.customerName}
</option>
);
};
const selectOptions = (props) => {
const customers = props.consumers.map((customer) => {
return (
<OptionItem
customerId={customer._id}
customerValue={customer.name}
customerCode={customer.customer_code}
customerName={customer.name}
/>
);
});
return (
<select
value={props.SelectElementValue}
onChange={props.selectCustomerHandler}
>
{/* <option key="1" value="1" disabled>
Select Customer
</option> */}
{customers}
</select>
);
};
然后将其传递给另一个无状态组件
<SelectItem
consumers={props.customers}
SelectElementValue={props.defaultValue}
selectCustomerHandler={props.customerSelectHandler}
/>
最后将其链接到状态组件
<ModalContent
dateLabel={this.state.dateLabel}
customers={this.state.customers}
defaultValue={this.state.selectCustomerDefault}
customerSelectHandler={this.customerSelect}
/>
期望的是,我应该能够将数据库中的customer._id
用作我的key
但不幸的是我遇到了错误
答案 0 :(得分:0)
您的OptionItem组件在我看来是需要密钥的组件。您正在创建它们并将它们分配给customers变量,然后将它们插入到您的select元素中。尝试将密钥添加到Consumers.map()中,如下所示。
const OptionItem = (props) => {
return (
<option key={props.customerId} value={props.customerValue}>
Code: {props.customerCode} Name: {props.customerName}
</option>
);
};
const selectOptions = (props) => {
const customers = props.consumers.map((customer) => {
return (
<OptionItem
key={customer._id} //I BELIEVE THIS IS THE MISSING KEY
customerId={customer._id}
customerValue={customer.name}
customerCode={customer.customer_code}
customerName={customer.name}
/>
);
});
return (
<select
value={props.SelectElementValue}
onChange={props.selectCustomerHandler}
>
{customers}
</select>
);
};
答案 1 :(得分:0)
收到此警告的原因是因为要在地图内渲染的组件需要一个键。有关密钥的更多信息,请参见React文档here。
从文档中,选择键的最佳方法是使用一个字符串,该字符串唯一地标识其同级项中的列表项。通常,您会将数据中的ID用作密钥。因此,在您的示例中,const customers = props.consumers.map((customer) => {
return (
<OptionItem
key={customer._id}
customerId={customer._id}
customerValue={customer.name}
customerCode={customer.customer_code}
customerName={customer.name}
/>
);
});
可以工作。
例如:
countdown