提问人:Olivialavie 提问时间:4/9/2023 更新时间:4/9/2023 访问量:87
是否可以只更新 map() 中的“查看更多”?
Is it possible to only update "see more" inside of map()?
问:
我正在练习一个使用 React.js 作为前端框架来展示产品的项目。我尝试按product_type过滤产品。获取数据时,我使用 slice() 在每个类别上显示 3 个产品,然后如果该类别中的产品超过 3 个,单击“查看更多”按钮,它将显示另外 3 个产品。
有没有办法只显示特定类别中的另外 3 种产品?现在,当我单击该按钮时,每个类别都会加载另外 3 个产品。
任何和所有的反馈都是值得赞赏的。谢谢!
App.js
import { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";
import Product from "./Product";
export default function App() {
const [products, setProducts] = useState([]);
const [productSlice, setProductSlice] = useState(3);
useEffect(() => {
axios
.get("https://www.allbirds.com/products.json?limit=50")
.then((response) => {
// All products return as an array of product objects
const { products } = response.data;
setProducts(products);
});
}, []);
return (
<div className="App">
<div>
{categories.map((cat, i) => (
<>
<div>
<h5 key={i}>{cat}</h5>
{products
.filter((type) => type.product_type === cat)
.slice(0, productSlice)
.map((product) => (
<Product data={product} />
))}
</div>
<p>
Total in {cat} :
{products.filter((type) => type.product_type === cat).length}
</p>
<button
onClick={() => {
// console.log("This is",cat);
products.filter((type) => type.product_type === cat).length >
2 && setProductSlice(productSlice + 1);
}}
>
See more
</button>
</>
))}
</div>
</div>
);
}
Products.js
export default function Product({ data }) {
const { images, title, handle } = data;
return (
<div key={handle}>
<h2>{title.split("-")[0]}</h2>
<div>
<img src={images[0].src} style={{ width: "100px" }} alt={handle} />
</div>
</div>
);
}
答:
2赞
Jone Polvora
4/9/2023
#1
您需要一个专用功能,可以根据需要处理您的数据。当从 API 获取数据后首次加载数据时,或者单击按钮请求更多数据时,可以打开此功能。
建议您在将此数据传递到组件之前使用此数据。这样,通过应用关注点分离,您将拥有更可读/更清晰的代码,而不是在组件上执行所有转换/逻辑。尽量让复杂的代码远离按钮、div、组件等
我的建议:
const [products, setProducts] = useState([]); //will contains the remote data
const [productSlice, setProductSlice] = useState([]); //will contains the current visible slice
const [sliceStart, setSliceStart] = useState(0);
const pageSize = 3;
const updateSlice = useCallback(() => {
const hasMore = products.length > currentIndex;
if (hasMore) {
//here we get the copy from products
const end = sliceStart + pageSize;
const nextItems = products.slice(sliceStart, end);
setProductSlice( old => [...old, ...nextItems]);
}
}, [products, sliceStart]);
useEffect(() => {
const fetchData = async () => {
const response = await axios.get("https://www.allbirds.com/products.json?limit=50");
// All products return as an array of product objects
const { products } = response.data;
setProducts(products);
}
fetchData().catch(err => console.error(err));
}, [updateSlice]);
return (
<>
<button
onClick={() => setSliceStart(prev => prev + pageSize)}>
See more
</button>
</>
)
希望能帮到你
3赞
Lynn C.
4/9/2023
#2
由于您希望在不同的类别中显示不同数量的产品,因此您可以定义一个状态来表示这些产品计数。productSlices
的初始值为productSlices
{
Shoes: 3,
Apparel: 3,
Socks: 3
}
例如,当您单击类别中的按钮时,值变为 4,其余值保持为 3。在地图操作中,您可以使用来获取类别中应显示的产品数量。Shoes
productSlices.Shoes
productSlices[cat]
您可以像这样修改代码:
import { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";
import Product from "./Product";
export default function App() {
const categories = ["Shoes", "Apparel", "Socks"];
const [products, setProducts] = useState([]);
const [productSlices, setProductSlices] = useState(
categories.reduce((a, v) => ({ ...a, [v]: 3 }), {})
);
useEffect(() => {
axios
.get("https://www.allbirds.com/products.json?limit=50")
.then((response) => {
// All products return as an array of product objects
const { products } = response.data;
console.log(products);
setProducts(products);
});
}, []);
return (
<div className="App">
<div>
{categories.map((cat, i) => (
<>
<div>
<h5 key={i}>{cat}</h5>
{products
.filter((type) => type.product_type === cat)
.slice(0, productSlices[cat])
.map((product) => (
<Product data={product} />
))}
</div>
<p>
Total in {cat} :
{products.filter((type) => type.product_type === cat).length}
</p>
<button
id={cat}
onClick={() => {
setProductSlices({
...productSlices,
[cat]: productSlices[cat] + 1
});
}}
>
See more
</button>
</>
))}
</div>
</div>
);
}
评论
1赞
Nick Parsons
4/9/2023
很好的答案,一个建议是同时传递一个函数,以避免在每次渲染时重新计算初始状态:useState()
useState(() => categories.reduce((a, v) => ({ ...a, [v]: 3 }), {}));
0赞
Olivialavie
4/10/2023
非常感谢!我还尝试获取类别 = [“鞋子”、“服装”、“袜子”];更具活力。我用它来获取类别......但它没有用。有什么建议吗?const categories = [ ...new Set(products.map((product) => product.product_type)) ];
1赞
Lynn C.
4/10/2023
@Olivialavie Make a state 并在钩子中设置它可能会起作用。在我的 codesandbox 中签出代码。categories
useEffect
评论