javascript - 如何在 React 中过滤或搜索对象数组?

标签 javascript reactjs

当我输入搜索特定事件或主持人时,出现错误。

这是搜索和过滤功能的所在(错误位于此处)

handleSearch = query => {
  this.setState({ searchQuery: query });
  this.getPagedData();
};

getPagedData = () => {
  const { searchQuery, events: allEvents } = this.state;

  let filtered = allEvents;
  if (searchQuery) {
    filtered = allEvents.filter(
      e =>
        e.title.toLowerCase().startsWith(searchQuery.toLowerCase()) ||
        e.hostName.toLowerCase().startsWith(searchQuery.toLowerCase())
    );
  }

  if (searchQuery.length === 0 || searchQuery.length === 1) {
    this.setState({
      events: getEvents()
    });
  } else {
    this.setState({
      events: filtered
    });
  }

  return { totalCount: filtered.length };
};

搜索框文件:

const SearchBox = ({ value, onChange }) => {
  return (
    <div className="search-box">
      <input
        className="search-txt"
        type="text"
        name="query"
        placeholder="search"
        value={value}
        onChange={e => onChange(e.currentTarget.value)}
      />
      <a className="search-btn" href="">
        <i className="fa fa-search" />
      </a>
    </div>
  );
};

搜索组件:

<SearchBox
  value={this.state.searchQuery}
  onChange={this.handleSearch}
/>

事件所在的fakeEvents文件:

const events = [
  {
    _id: "1",
    eventPicture: "event1.jpeg",
    hostID: "111",
    hostPicture: "profile1.jpg",
    eventTime: "Aug 1, Thu 8:00pm",
    title: "Basketball",
    numberOfAtendies: "12 people are attending",
    location: "5 miles away",
    details:
      "this is a 5 on 5 basketball game and I am looking for advanced players best 2 games out of 3 this is a 5 on 5 basketball game and I am looking for advanced players best 2 games out of 3 this is a 5 on 5 basketball game and I am looking for advanced players best 2 games out of 3.",
    category: { _id: "1and1", name: "Sports" },
    liked: ""
  },

用户信息来自的 fakeUsers 文件:

const users = [
  {
    _id: "111",
    name: "Sami Baghban",
    age: "20",
    picture: "profile1.jpg",
    interests: [
      "Basketball",
      "Soccer",
      "Movies",
      "Coding",
      "Shopping",
      "Football",
      "Hiking"
    ],
    discription:
      "Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat maiores non aliquid pariatur iste aspernatur sapiente sunt voluptatem necessitatibus, nostrum eaque nulla alias porro nisi quisquam tempora minima cupiditate quidem!",
    numOfFriends: 400,
    numOfEvents: 50
  },

事件文件的状态:

class Events extends Component {
  state = {
    events: getEvents(),
    user: getUser(),
    users: getUsers(),
    showDetails: false,
    shownEventID: 0,
    showUserProfile: false,
    shownUserID: 0,
    searchQuery: ""
  };

错误消息:

TypeError: Cannot read property 'toLowerCase' of undefined
allEvents.filter.e
src/components/events.jsx:108
105 |
106 | let filtered = allEvents;
107 | if (searchQuery) {
> 108 |   filtered = allEvents.filter(
    | ^  109 |     e =>
  110 |       e.title.toLowerCase().startsWith(searchQuery.toLowerCase()) ||
  111 |       e.hostName.toLowerCase().startsWith(searchQuery.toLowerCase())

最佳答案

您的实现非常复杂,让我们尝试简化一下。

这是一个非常相似的工作示例,但确实使用了 React Hooks

注意:如果您仍在掌握 React,您可能还不想查看 hooks。如果您克服了最初的障碍,那么它们就很棒。

import React, { useState } from "react";
import items from "./items";

const SearchExample = () => {
  const [filterText, setFilterText] = useState("");

  const filteredItems = items.filter(
    item =>
      item.description.toLocaleLowerCase().includes(filterText) ||
      item.title.toLocaleLowerCase().includes(filterText)
  );

  const itemsToDisplay = filterText ? filteredItems : items;

  return (
    <div style={{ padding: "20px 50px" }}>
      <h1>Search Page</h1>
      <input
        type="text"
        placeholder="Filter items by keyword"
        value={filterText}
        onChange={e => setFilterText(e.target.value.toLocaleLowerCase())}
      />
      <hr />
      {!filteredItems.length && (
        <div>There are no items to display adjust your filter criteria</div>
      )}
      {itemsToDisplay.map(item => (
        <div key={item.title}>
          <h3>{item.title}</h3>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
};

export default SearchExample;

其中 items 是一个数组,例如:

export const items = [
  {
    title: "React",
    description:
      "React (also known as React.js or ReactJS) is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies."
  }
]

关于javascript - 如何在 React 中过滤或搜索对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57861003/

相关文章:

javascript - React router 4查询参数示例不起作用

reactjs - 如何处理一个重载中存在而另一重载中不存在的属性?

javascript - 语义用户界面 : How to set up a list of values onto a dropdown using javascript?

javascript - 更改 Material UI 选择器上的工作日标签

javascript - 将一个隐藏的 div 复制到另一个 div

javascript - 按数字顺序对本地存储键进行排序

javascript - React-Redux 从 5.x 迁移到 7.x 失败 `connect`

javascript - 第一页打开为空,未加载数据

javascript - 如何使用 jquery 操作动态创建的元素?

javascript - 在检查谷歌表单的输入元素时,我找不到 "name"属性。如何找到它?