在REACT中搜索时合并多个字段



我有3个搜索字段,如下所示:在此处输入图像描述

我在搜索时组合了两个第一个字段,但不知道如何组合最后一个。这是我组合两个第一个字段的代码:

import React from 'react';
import Nav from '../components/Nav';
import FixedNav2 from '../components/FixedNav2';
import Footer from '../components/Footer';
import '../styles/style.scss';
import RatedRecipeItem from '../components/RatedRecipeItem';
class Recipe extends React.Component {
constructor(props){
super(props)
this.state = {
recipes: [],
// filterList:{
category: "",
cuisine:"",
sort:"",
// },
dataIsReturned :false
}
this.handleChangeCategory = this.handleChangeCategory.bind(this);
this.handleChangeCuisine = this.handleChangeCuisine.bind(this);
this.handleChangeSort = this.handleChangeSort.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async componentDidMount(){
const pathname = 'http://localhost:4000/recipes/';
const data = await fetch(pathname);
const recipes = await data.json();
recipes.forEach(recipe => {
const newDate = new Date(recipe.date);
const day = newDate.getDate();
const month = newDate.getMonth()+1;
const year = newDate.getFullYear();
recipe.date = day+'-'+month+'-'+year;
});
this.setState({
recipes:recipes,
dataIsReturned:true
})  
}
handleChangeCategory(event){
this.setState({category:event.target.value })
}
handleChangeCuisine(event){
this.setState({cuisine:event.target.value })
}
handleChangeSort(event){
this.setState({sort:event.target.value })
}
handleSubmit(event){
}
getUnique(arr, comp) {
// store the comparison  values in array
const unique =  arr.map(e => e[comp])
// store the indexes of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)
// eliminate the false indexes & return unique objects
.filter((e) => arr[e]).map(e => arr[e]);
return unique;
}

render() {
const recipes = this.state.recipes;
const dataIsReturned = this.state.dataIsReturned;
if(!dataIsReturned){
return <div>LOADING...</div>
}
const uniqueCategory = this.getUnique(recipes,"category");
const uniqueCuisine = this.getUnique(recipes,"cuisine");
const category = this.state.category;
const cuisine = this.state.cuisine;
const sort = this.state.sort;
console.log(category,cuisine,sort);
// console.log(cuisine === "");
// console.log(uniqueCategory);

const filterRecipes = recipes.filter(function(recipe) {
// console.log(recipe.category)
if(cuisine && category)
return recipe.category === category && recipe.cuisine === cuisine
else if(!cuisine && category)
return recipe.category === category
else if(cuisine && !category)
return recipe.cuisine === cuisine
else return []
});
console.log(filterRecipes);
return(
<section className="recipe-section">
<Nav/>
<FixedNav2/>
<div className="container">
<div className="search">
<div className="search__content">
<form className="flex flex-jc-sb" onSubmit={this.handleSubmit}>
<div className="search__group flex">
<label for="recipe-category">
Recipe Category
</label>
<select className="recipe-select" value={this.state.category} onChange={this.handleChangeCategory}>
<option selected> - Select - </option>
{uniqueCategory.map(recipe => 
<option key={recipe._id} value={recipe.category}>
{recipe.category}
</option>
)}
</select>
</div>
<div className="search__group flex">
<label for="recipe-category">
Recipe Cuisine
</label>
<select className="recipe-select" value={this.state.cuisine} onChange={this.handleChangeCuisine}>
<option selected> - Select - </option>
{uniqueCuisine.map(recipe => 
<option key={recipe._id} value={recipe.cuisine}>
{recipe.cuisine}
</option>
)}
</select>
</div>
<div className="search__group flex">
<label for="recipe-category">
Sort recipes
</label>
<select className="recipe-select" value={this.state.sort} onChange={this.handleChangeSort}>
<option selected> - Select - </option>
<option value="Top rated">
Top rated
</option>
<option value="Latest">
Latest
</option>
<option value="Most favourited">
Most favourited
</option>
</select>
</div>
<div className="search__group">
<input type="Submit" value="Search for recipes"/>
</div>
</form>
</div>
</div>
<div className="recipe-list flex flex-jc-sb flex-ai-c">
{
(filterRecipes.length !== 0) ?
filterRecipes.map(recipe => 
<RatedRecipeItem recipeID={recipe._id} images={recipe.image} 
authorID={recipe.user._id} date={recipe.date}
avatars={recipe.user.avatar} authorsName={recipe.user.fullname} 
foodTitles={recipe.title} foodDescriptions={recipe.description} 
difficulty={recipe.difficulty} yeild={recipe.yeild} 
numOfPeople={recipe.numOfPeople} times={recipe.times}
cuisine={recipe.cuisine} category={recipe.category}
ingredients={recipe.ingredients} steps={recipe.steps}/>
)
:( (category !== "" || cuisine !== "") ? <div>There is no recipe you want to find.</div>
:   recipes.map(recipe => 
<RatedRecipeItem recipeID={recipe._id} images={recipe.image} 
authorID={recipe.user._id} date={recipe.date}
avatars={recipe.user.avatar} authorsName={recipe.user.fullname} 
foodTitles={recipe.title} foodDescriptions={recipe.description} 
difficulty={recipe.difficulty} yeild={recipe.yeild} 
numOfPeople={recipe.numOfPeople} times={recipe.times}
cuisine={recipe.cuisine} category={recipe.category}
ingredients={recipe.ingredients} steps={recipe.steps}/>
)
)
}
</div>
</div>
<Footer/>
</section>
)
}
}
export default Recipe;

在上面的代码中,我从用户选择的选项中获得了美食和类别,并声明了变量filterRecipes来存储过滤后的结果。最后一个选项包括:Top Rated(numOfLike(、Most Favorite(numOfFavorited(和Latest(date(:在此处输入图像描述,这意味着我必须对我的食谱数组进行排序,并与2个第一字段组合。有人能帮我解决这个问题吗?这是我的配方结构

category: "Desert"
cuisine: "Italia"
date: "22-4-2021"
description: "Pizza, dish of Italian origin consisting of a flattened disk of bread dough topped with some combination of olive oil, oregano, tomato, olives, mozzarella or other cheese, and many other ingredients, baked quickly"
difficulty: "Medium"
image: "https://www.recipe30.com/wp-content/uploads/2017/02/fried-pizza-848x477.jpg"
ingredients: (4) ["Egg", "Bread", "Milk", "Tomato"]
numOfFavourited: 5
numOfLike: 3
numOfPeople: "5 people"
steps: (7) ["Preheat pizza stone (or pizza pan or baking sheet):", "Divide the dough into two balls:", "Prep toppings:", "Flatten dough ball, and stretch out into a round:", "Brush dough top with olive oil: ", "Sprinkle pizza peel with corn meal, put flattened dough on top", "Spread with tomato sauce and sprinkle with toppings:"]
times: "1 hour"
title: "Pizza"
user: {favouritedRecipes: Array(0), recipes: Array(0), numOfLike: 4, _id: "608150e51553791e9486bb8c", fullname: "Do Quang Huy", …}
yeild: "A pack"
__v: 0
_id: "6081513899b23b41bca9b605"

如果我正确理解这个问题,我想你想做这样的事情:

const filterRecipes = recipes.filter(r => {
if (cuisine && r.cuisine !== cuisine) return false;
if (category && r.category !== category) return false;
return true;
} )
const sorted = filterRecipes.sort((a, b) => b.numOfLike - a.numOfLike)

最新更新