gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:34:28 25 4
gpt4 key购买 nike

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com