我想重新加載一組物件并根據搜索輸入值使其顯示。
例如,有一個搜索輸入和一個評論串列(標題 評論)。
當用戶在搜索輸入中鍵入“a”時,將重新加載串列并為您提供標題中包含“a”的串列。標題中不包含“a”的專案將不會出現。
當用戶在搜索輸入中鍵入“ab”時,串列將重新加載并為您提供標題中包含“ab”的串列。標題中不包含“ab”的專案將不會出現。
您可以在此處查看我當前的迷你專案:https : //distracted-golick-f00481.netlify.app/
您可以添加評論串列并將其保存到本地存盤中。該串列將按字母順序和更高的排名排序。
==========
Reviews.js(包括評論串列)
import React, { useState } from "react";
import Header from "./Header";
import Review from "./Review";
import Input from "./Input";
const Reviews = ({ books, initialData }) => {
const combinedBooks = initialData.concat(books);
const [myBooks, setMyBooks] = useState(combinedBooks);
const [searchTerm, setSearchTerm] = useState("");
// sort by rank
let sorted = combinedBooks.sort((a, b) => {
return b.score - a.score;
});
// sort by alphabetical order
let newSorted = sorted.sort(function (a, b) {
let fa = a.title.toLowerCase(),
fb = b.title.toLowerCase();
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
});
// sort by rank then alphabetically
let newerSorted = [...newSorted].sort((a, b) => {
return b.score - a.score;
});
// Reload the data based on the search input value.. BUT How?
return (
<section style={{ border: "3px solid green" }}>
<Header title="Book Review Lists" />
{/* search input to find the book review by title */}
<form>
<Input
smallTitle=""
placeholder="find the review by title"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</form>
<h1>{searchTerm}</h1>
{newerSorted.map((review) => {
const { id, title, comment, score } = review;
return (
<Review key={id} title={title} comment={comment} score={score} />
);
})}
</section>
);
};
export default Reviews;
uj5u.com熱心網友回復:
您可以在映射newerSorted陣列之前直接行內過濾searchTerm值包含在其title屬性中的評論。
{newerSorted.filter(({ title }) => title.toLowerCase().includes(searchTerm.toLoweCase()))
.map(({ id, title, comment, score }) => (
<Review key={id} title={title} comment={comment} score={score} />
))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359535.html
標籤:javascript 反应 反应钩子 重新加载数据
