reactjs - 不使用提供的密钥道具做出反应
问题描述
我在https://codesandbox.io/s/cranky-faraday-ucilw?file=/src/App.js运行模糊搜索测试
但是,即使我传入了唯一 ID,它也不接受唯一密钥道具。
我究竟做错了什么?
这是错误:
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `MyComponent`.
in ul (at search.jsx:25)
in MyComponent (at App.js:13)
in div (at App.js:12)
in App (at src/index.js:9)
in StrictMode (at src/index.js:8)
App.js 代码:
import React, { Component } from "react";
import MyComponent from "./search";
const customers = [
{ id: "1", name: "Bob", email: "aa@aa.com" },
{ id: "2", name: "Foo", email: "mm@mm.com" }
];
export default class App extends Component {
render() {
return (
<div>
<MyComponent customers={customers} />
</div>
);
}
}
Search.js 代码:
import React from "react";
import useFuse from "react-use-fuse";
function MyComponent({ customers }) {
const options = {
keys: ["name", "email"]
};
const { result, search, term } = useFuse({
data: customers,
options
});
return (
<div>
<input
onChange={e => search(e.target.value)}
value={term}
placeholder="Search for a customer..."
/>
{console.log(term)}
{result &&
result.map(customers => (
<ul key={customers.id}>
<li>{customers.name}</li>
<li>{customers.email}</li>
</ul>
))}
</div>
);
}
export default MyComponent;
解决方案
问题在于您的result
数组,当您过滤它时,它的结构会发生变化。
未过滤:
[{id, name, email}, ...]
过滤:
[{ item: {id, name, email } }, ...]
因此,当您映射时result
,因此没有id
错误消息。
解决此问题的一种方法是检查 map 返回的对象是否具有名为的属性item
:
{result &&
result.map(customer => {
if (customer.item) customer = customer.item;
return (
<div key={customer.id}>
<p>{customer.name}</p>
<p>{customer.email}</p>
</div>
);
})}
顺便说一句,我customers
在 map 中重命名为customer
,因为customers
已经声明为props
推荐阅读
- python - 我如何在熊猫中解决这个问题?
- c - 2D 动态分配的数组可以访问比分配大小更多的内存
- c# - 如何直接从 DLL 访问 SQLite 数据库(不使用 app.config)?
- javascript - 当我连续两次执行一个简单的JS函数时,是否会花费两倍的计算能力?
- regex - 奇数个 a 和奇数个 b 的正则表达式
- php - 如何在 COUNT(*) 中显示我的查询结果
- 清单包括号码?
- ruby-on-rails - 如何为等待的工人建立规范
- python - 可以在 for 循环中定义 self 变量吗?
- ember.js - 在覆盖 Ember 成员函数时,我是否应该始终包含 this._super(...arguments)
- javascript - Laravel 依赖选择