我有一个从api中提取的列表。这个列表将根据输入进行过滤。但是在第一次呈现时,它将什么都不呈现,除非我按空格键或在输入中添加任何内容。
当我点击按钮时,它会过滤,但我希望在第一次渲染时,在点击之前显示整个列表
import Button from "react-bootstrap/Button";
import Card from "react-bootstrap/Card";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import { useEffect, useState } from "react";
function News() {
const [news, setNews] = useState([]);
const [listing, setLists] = useState([]);
const fetchDataList = () => {
return fetch("https://api.npoint.io/d275425a434e02acf2f7")
.then((response) => response.json())
.then((data) => {
setLists(data.News);
// data.News[0].id = 0;
console.log(listing);
});
};
useEffect(() => {
fetchDataList();
}, []);
const fetchData = () => {
return fetch("https://api.npoint.io/91298d970c27e9a06518")
.then((response) => response.json())
.then((data) => {
setNews(data.newsCategory);
console.log(news);
});
};
useEffect(() => {
fetchData();
}, []);
const [filteredCat, setFiltredCat] = useState(null);
useEffect(() => {
setFiltredCat(setLists());
}, []);
function filteredCategory(typecat) {
let filteredCategory = listing.filter(
(type) => type.categoryID === typecat
);
return filteredCategory;
}
function handleCategory(e) {
let typeCategory = e.target.id
typeCategory
? setFiltredCat(filteredCategory(typeCategory))
: filteredCategory(setLists);
}
return (
<>
<p>Media</p>
<h2>Top </h2>
<div>
{news &&
news.map((idx) => (
<Button id={idx.id} variant="secondary" onClick={handleCategory}>
{idx.id} {idx.name}
</Button>
))}
</div>
<Container>
<Row>
<Col>
{filteredCat &&
filteredCat.map((list) => (
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src="holder.js/100px180" />
<Card.Body>
<Card.Title>{list.title}</Card.Title>
<Card.Text>{list.description}</Card.Text>
<Button variant="primary">{list.categoryID}</Button>
</Card.Body>
</Card>
))}
</Col>
</Row>
</Container>
</>
);
}
export default News;
1条答案
按热度按时间nfs0ujit1#
当数据进入时,您还需要设置类别,
在您的
setNews(data.newsCategory);
下面,您可以添加setFiltredCat(filteredCategory(news[0].id.toString()));
编辑:
为了确保在设置初始过滤器之前已经设置了news,你还可以添加一个钩子来监视
news
的变化。编辑:要返回所有列表,最初可以使用相同的概念