警告:在React中实现搜索过滤器时遇到两个具有相同键的孩子

问题描述 投票:0回答:1

我是React的新手,我一直在尝试对我拥有的数据实施搜索过滤器。但是,在搜索栏中输入查询时,我在控制台中收到此错误。

index.js:1 Warning: Encountered two children with the same key, `.$-M9EdZMRAOiy_QUS1yKA`. 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.
in ul (created by ForwardRef(GridList))
in ForwardRef(GridList) (created by WithStyles(ForwardRef(GridList)))
in WithStyles(ForwardRef(GridList)) (at space-card-grid.tsx:32)
in SpaceCardGrid (at search.tsx:59)
in div (at search.tsx:58)
in div (created by Col)
in Col (at search.tsx:57)
in div (created by Row)
in Row (at search.tsx:56)
in div (created by Container)
in Container (at search.tsx:55)
in div (at search.tsx:45)
in SearchPage (created by Context.Consumer)
in Route (at routes.tsx:9)
in Switch (at routes.tsx:8)
in Routes (at src/index.tsx:15)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.tsx:14)
in div (at src/index.tsx:13)
in FirebaseProvider (at src/index.tsx:11)

即使我试图一次又一次地输入,也会遇到重复错误,导致应用程序崩溃。这是我为搜索过滤器编写的代码。

import React, { useRef, useState, useEffect } from 'react';
import { Col, Container, Row } from 'react-bootstrap';
import SpaceCardGrid from '../space-card-grid/space-card-grid';
import { MDBCol } from 'mdbreact';
import { firebaseDb } from '../../utils/firebase/index';

type SpaceType = {
  id: string;
  description: string;
  title: string;
  imageId: number;
  likes: number;
  eventDate: string;
  startTime: string;
  endTime: string;
};

const allSpaces: SpaceType[] = [];
const SearchPage = () => {
  const [spaces, setSpaces] = useState<SpaceType[]>([]);

  firebaseDb.ref(`studios`).once('value', (snapshot) => {
    snapshot.forEach((space) => {
      allSpaces.push({ ...space.val(), id: space.key });
    });
    setSpaces(allSpaces.reverse());
  });

  const [searchQuery, setSearchQuery] = useState({ query: '' });
  const spaceCardGridRef = useRef(null);

  const searchQueryHandler = (event) => {
    setSearchQuery({ query: event.target.value });
    event.preventDefault();
  };

  let filteredspaces = spaces;

  if (searchQuery.query !== '')
    filteredspaces = spaces.filter((space) => {
      return space.title.toLowerCase().indexOf(searchQuery.query.toLowerCase()) !== -1;
    });

  return (
    <div>
      <br></br>
      <MDBCol md="6">
        <input
          className="form-control"
          placeholder="Search spaces of interest"
          onChange={searchQueryHandler}
          value={searchQuery.query}
        />
      </MDBCol>
      <Container fluid className="bottom-container">
        <Row style={{ justifyContent: 'center', alignItems: 'flex-start' }}>
          <Col>
            <div className="grid-root">
              <SpaceCardGrid spaces={filteredspaces} spaceCardGridRef={spaceCardGridRef} />
            </div>
          </Col>
        </Row>
      </Container>
    </div>
  );
};

export default SearchPage;

我正在从firebase读取数据,然后使用它(我怀疑问题在这里)。所有数据正在正确读取并显示在屏幕上。该问题仅在我开始搜索时出现。

为了更加清晰,我附上了浏览器的屏幕截图。

Screenshot of my browser

reactjs typescript firebase search react-hooks
1个回答
0
投票

GridList组件中,可以通过将元素的索引附加到末尾来使映射数组的键更唯一,例如:

items.map((item, index) => <GridItem key={`item.id-index`}>{/* ...your logic... */});
© www.soinside.com 2019 - 2024. All rights reserved.