首页 > 解决方案 > 过滤年龄范围 React.js

问题描述

我有一个 React.js 应用程序。我有一个搜索页面组件,我在其中按位置、年龄、品种和性别搜索宠物。我的搜索输入都是选择框(我使用 formik 进行表单处理)。我的年龄输入有问题。我想把它作为一个选择框,我可以在其中选择一些年龄范围(< 3、> 3、All)。但我不知道如何将其作为数据和过滤器部分。其他输入都有效,但年龄不起作用,因为它是我假设的字符串。而且我不太擅长将字符串转换为数字。 在此处输入图像描述 这是我下面的代码

Data.js

export let searchGuests = {
    searchGuestsTitle: {
      title: "Adopt Your New Pet",
    },
    guestsResults: [
      {
        id: 1,
        img:
          "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F37%2F2020%2F09%2F22%2F50-cute-dog-names.jpg",
        location: "Istanbul",
        age: "2",
        breed: "Poodle",
        gender: "Female",
        name: "Sushi",
      },
      {
        id: 2,
        img:
          "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F37%2F2020%2F09%2F22%2F50-cute-dog-names.jpg",
        location: "Istanbul",
        age: "1",
        breed: "Terrier",
        gender: "Male",
        name: "Sushi",
      },
      {
        id: 3,
        img:
          "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F37%2F2020%2F09%2F22%2F50-cute-dog-names.jpg",
        location: "Istanbul",
        age: "2",
        breed: "Poodle",
        gender: "Female",
        name: "Sushi",
      },
    ],
    locationCities : [
      "Istanbul",
      "Ankara",
      "Izmir"
    ],
    searchBreed : [
      "Poodle",
      "Terrier",
      "Rottweiler",
      "Golden Retriever",
      "Cat",
      "Tobby cat",
      "Scottish"
    ],
    searchAge : [
      "<3",
      ">3",
      "All"
    ]
  };
Search.js

import React, { useState } from "react";
import SearchResults from "./SearchResults";
import { Container, Row, Col } from "react-bootstrap";
import { FaSearch } from "react-icons/fa";
import "./Search.css";
import { useFormik } from 'formik';

const Search = ({ searchGuests }) => {

  const [searchResults, setSearchresults] = React.useState([])

  const formik = useFormik({
    initialValues: {
      location: "",
      age: "",
      breed: "",
      gender: "",
    },
    onSubmit: values => {
      const searchItem = searchGuests.guestsResults.filter(item => {
        return (
          item.location
            .toLowerCase()
            .includes(
              values.location.toLowerCase()
            ) &&
          item.age
            .toLowerCase()
            .includes(
              values.age.toLowerCase()
            ) &&
          item.breed
            .toLowerCase()
            .includes(
              values.breed.toLowerCase()
            ) &&
          item.gender
            .toLowerCase()
            .includes(
              values.gender.toLowerCase()
            )
        )
      })
      return setSearchresults(searchItem)
      // return JSON.stringify(values, null, 2);
    },
  });

  const LoadingPage = () => {
    return (
      <Col sm={12} className="loadPage">
        <h4>Start Searching Now and Discover New Friends</h4>
        <h6>They are waiting for their new home</h6>
        <img src="https://timesofindia.indiatimes.com/photo/67586673.cms" className="w-100 searchCatLogo" />
      </Col>
    );
  };

  return (
    <Container>
      <Row className="searchContainer py-5">
        <h1>{searchGuests.searchGuestsTitle.title}</h1>
        <Col sm={12}>
          <form onSubmit={formik.handleSubmit} className="searchForm">
            <label htmlFor="location"></label>
            <select id="location" name="location" value={formik.values.location} {...formik.getFieldProps('location')}>
              <option value="Select Location">Select Location</option>
              {searchGuests.locationCities.map(city => <option>{city}</option>)}
            </select>

            <label htmlFor="age"></label>
            <select id="age" name="age" value={formik.values.age} {...formik.getFieldProps('age')}>
              <option value="Select Age">Select Age</option>
              {searchGuests.SearchAge.map(age => <option>{age}</option>)}
            </select>

            <label htmlFor="breed"></label>
            <select id="breed" name="breed" value={formik.values.breed} {...formik.getFieldProps('breed')}>
              <option value="Select Breed">Select Breed</option>
              {searchGuests.searchBreed.map(breed => <option>{breed}</option>)}
            </select>

            <label htmlFor="gender"></label>
            <select name="gender" value={formik.values.gender} {...formik.getFieldProps('gender')}>
              <option value="Select Gender">Select Gender</option>
              <option value="Female">Female</option>
              <option value="Male">Male</option>
            </select>

            <button type="submit">
              <FaSearch size={27} className="searchIcon" />
            </button>
          </form>
        </Col>
        <Col sm={12}>
          <Row className="mt-5 items">
            {searchResults.length > 0 ? searchResults.map(result => {
              return (
                <SearchResults
                  key={result.id}
                  img={result.img}
                  location={result.location}
                  age={result.age}
                  breed={result.breed}
                  gender={result.gender}
                  name={result.name}
                />
              )
            }) : <LoadingPage />}
          </Row>
        </Col>
      </Row>
    </Container>
  );
};

export default Search;
SearchResults.js

import React, { useState } from "react";
import { Col, Button, Card } from "react-bootstrap";
import "./Search.css";
import { BsGeoAlt } from "react-icons/bs";
import { FaPaw } from "react-icons/fa";
import AdoptionFormModal from "./AdoptionFormModal"


const SearchResults = ({ img, id, location, age, breed, gender, name }) => {

  const [modalShow, setModalShow] = useState(false);

    return (
        <>
            <Col lg={4} className="mb-5">
                <Card style={{ width: '18rem' }}>
                    <Card.Img variant="top" src={img} />
                    <Card.Body id="modalBody">
                        <Card.Text id="cardText">
                            <div className="firstDiv">
                                <p>{breed}</p>
                                <p>{name}</p>
                                <Button variant="primary" className="adoptButton shadow-none" onClick={() => setModalShow(true)}>
                                    <FaPaw className="pawIcon"/>
                                    Adopt
                                </Button>
                            </div>
                            <div className="secondDiv">
                                <p>{gender}, {age}</p>
                                <p className="mt-4"><BsGeoAlt size={25}/> {location}</p>
                            </div>
                        </Card.Text>
                    </Card.Body>
                </Card>
            </Col>
            <AdoptionFormModal
              show={modalShow}
              onHide={() => setModalShow(false)}
            />
        </>
    );
};

export default SearchResults;

标签: reactjsfilterreact-hooksformik

解决方案


似乎您需要一种针对 3 个年龄类别的“切换”语句。

const checkAge = age => {
  switch(values.age.toLowerCase()) {
    case "<3":
      return Number(age) < 3;
    case ">3"
      return Number(age) >= 3;
    case "all":
    default:
      return true;
  }
};

...

return (
  item.location
    .toLowerCase()
    .includes(
      values.location.toLowerCase()
    ) &&
    checkAge(item.age) &&
    item.breed
      .toLowerCase()
      .includes(
        values.breed.toLowerCase()
    ) &&
    item.gender
      .toLowerCase()
      .includes(
        values.gender.toLowerCase()
    )
)

推荐阅读