Heim > Fragen und Antworten > Hauptteil
Hier ein Überblick über das, was ich bisher versucht habe:
Datenfilterfunktion
function filterData(searchText, restaurants) { const filterData = restaurants.filter((restaurant) => restaurant.info.name.includes(searchText) ); return filterData; }
import { restruntList } from "../constants"; // JSON数据 const Body = () => { const [searchText, setSearchText] = useState(""); const [restaurants, setRestaurants] = useState(restruntList); return ( <> <div className="search-container"> <input type="text" className="search-input" placeholder="搜索" value={searchText} onChange={(e) => { setSearchText(e.target.value); }} /> <button className="search-btn" onClick={() => { //过滤数据 const data = filterData(searchText, restaurants); //更新状态 - restaurant变量 setRestaurants(data); }} > 搜索{" "} </button> </div> //UI <div className="restrunt-list"> {restruntList.map((restaurant) => { return <RestruntCard {...restaurant.info} key={restaurant.info.id} />; })} </div> </> ); };
restruntList JSON-Datenformat
export const restruntList = [ { info: { id: "23719", name: "麦当劳", cloudinaryImageId: "ee5f8e06b300efc07c9fe3f4df40dfc4", locality: "JM Road", areaName: "Shivajinagar", costForTwo: "₹400 for two", cuisines: ["汉堡", "饮料", "咖啡馆", "甜点"], avgRating: 4.3, } } ]
P粉8659009942023-09-21 00:18:34
根据您提供的代码和描述,这种方法看起来大部分是正确的,但在处理过滤数据函数和餐厅数据的方式上存在一个小问题。
主要问题在于您如何处理过滤和更新状态。由于React的状态更新是异步的,直接使用searchText
值来过滤restaurants
可能无法得到预期的结果。状态更新可能在设置searchText
后没有立即发生,因此您可能会得到不一致或过时的过滤结果。
为了解决这个问题,您可以利用useEffect
钩子在searchText
更改时更新过滤数据。这样,过滤函数将始终操作最新的状态。以下是更新后的代码:
import React, { useState, useEffect } from 'react'; import { restruntList } from '../constants'; function filterData(searchText, restaurants) { const filteredData = restaurants.filter((restaurant) => restaurant.info.name.toLowerCase().includes(searchText.toLowerCase()) ); return filteredData; } const Body = () => { const [searchText, setSearchText] = useState(''); const [filteredRestaurants, setFilteredRestaurants] = useState(restruntList); useEffect(() => { const data = filterData(searchText, restruntList); setFilteredRestaurants(data); }, [searchText]); return ( <> <div className="search-container"> <input type="text" className="search-input" placeholder="搜索" value={searchText} onChange={(e) => setSearchText(e.target.value)} /> </div> <div className="restaurant-list"> {filteredRestaurants.map((restaurant) => ( <RestruntCard {...restaurant.info} key={restaurant.info.id} /> ))} </div> </> ); }; export default Body;
代码中的更改:
restaurants
更改为filteredRestaurants
,以避免原始数据和过滤数据之间的混淆。useEffect
钩子来处理searchText
更改时的过滤。这确保了过滤数据的正确更新。现在,当您在搜索输入框中输入时,过滤应立即生效,并相应地更新餐厅列表。