[英]How to Display "No Items Were Found" React.js
I have a React.js App where I search pets as below我有一个 React.js 应用程序,我可以在其中搜索宠物,如下所示
When the page first loads, I display some text and image.当页面首次加载时,我会显示一些文本和图像。 Then user makes a search and gets the results according to the search.
然后用户进行搜索并根据搜索得到结果。 But if there is no matching results, I want to display a message as "No Items were found" How can I do this?
但是如果没有匹配的结果,我想显示一条消息“没有找到项目”我该怎么做? My if condition is not working in the submit function.
我的 if 条件在提交 function 中不起作用。
Below is my code下面是我的代码
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()
)
)
})
if(searchItem) {
return setSearchresults(searchItem)
} else {
return searchResults("No Items Were Found")
}
// 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>
<input
id="age"
type="text"
placeholder="age"
{...formik.getFieldProps('age')}
/>
<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;
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"
]
};
You can render it based on the type of searchResults
is a string or array可以根据
searchResults
的类型是字符串还是数组来渲染
{/* Show result */}
{searchResults.length > 0 &&
Array.isArray(searchResults) &&
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}
/>
);
})}
{/* Show notfound */}
{searchResults.length > 0 && typeof searchResults === "string" && (
<div>{searchResults}</div>
)}
{/* Show loading */}
{searchResults.length === 0 && <LoadingPage />}
if(searchItem.length > 0) {
return setSearchresults(searchItem)
} else {
return searchResults("No Items Were Found")
}
First: You are directly mutated the state, so your component won't re-render:第一:你直接改变了 state,所以你的组件不会重新渲染:
return searchResults("No Items Were Found")
And also it's inefficient to save error state the same state you store your response, so create another state for that:而且将错误 state 保存为与存储响应相同的 state 也是低效的,因此为此创建另一个 state:
const [error, setError] = React.useState('')
And then set your error like this:然后像这样设置你的错误:
setError("No Items Were Found")
return;
Lastly, check for the existent of error and render it:最后,检查是否存在错误并渲染它:
{error && <p>{error}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.