首页 > 解决方案 > 不使用提供的密钥道具做出反应

问题描述

我在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;

标签: reactjs

解决方案


问题在于您的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


推荐阅读