如何在 React.js 中按类别显示产品

How to display Products By Category in React.js

大家好,我是 React 初学者 我正在使用 React.js 并尝试显示来自 public API 的类别,它在我的应用程序中成功显示 现在我试图分别显示每个类别的产品 这样,如果我单击特定类别,该类别的所有产品将显示在单独的页面上

App.js

import React from 'react';
import './App.css';
import {BrowserRouter,Routes,Route} from "react-router-dom";
import Categories from './components/Categories';
import Items from './components/Items';
function App() {


  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route path="/" exact element={<Categories />}/>
          <Route path="/items" element={<Items />}/>
        </Routes>
        {/* <Items /> */}
      </BrowserRouter>
    </div>
  );
}

export default App;

Categories.js

import React, { useState, useEffect } from 'react';
import '../style/Categories/categories.css'
import axios from 'axios'
const Categories = () => {

    const [categories, setCategories] = useState([])
    useEffect(() => {
        const getCategory = async () => {
            const res = await axios.get('https://api.publicapis.org/categories')
            setCategories(res.data.categories)
            console.log("res.data", res.data);
        }
        getCategory()
    }, [])
    return (
        <>
            <h1 style={{ textAlign: 'center' }}>All Categories</h1>
            <div className="category__wrapper">
                {categories.map(category =>
                    <div key={Math.random()} className="category__item">
                        <h2><a href="#" >{category}</a></h2>
                    </div>
                )}
            </div>
        </>
    )
}

export default Categories

Items.js

import React, { useState, useEffect } from 'react';
import axios from 'axios'
import '../style/Items/items.css'


const Items = () => {
    const [items, setItems] = useState([])
    useEffect(() => {
        const getItems = async () => {
            const result = await axios.get('https://api.publicapis.org/entries')
            setItems(result.data.entries)
            console.log("result.entries", result.data.entries);
        }
        getItems()
    }, [])
    return (
        <div className="item__wrapper">
            {items.map((item) => (
                <div class="ui card" key={item.API}>
                    <div class="content">
                        <div class="header">{item.API}</div>
                    </div>
                    <div class="content">
                        <p>{item.Description}</p>
                        <span>Category: {item.Category}</span>
                    </div>
                    <div class="extra content">
                        <button class="ui button">Show More</button>
                    </div>
                </div>
            ))}
        </div>
    )
}

export default Items

App.js

- <Route path="/items" element={<Items />}/>
+ <Route path="/items/:categoryId" element={<Items />}/>

Categories.js

+ import { Link } from "react-router-dom"

- <h2><a href="#" >{category}</a></h2>

+ <h2>
+   <Link to={`/items/${category.id}`}>{category}</Link>
+ </h2>

Items.js

const Items = () => {
+  const { categoryId } = useParams()

  const [items, setItems] = useState([])

  useEffect(() => {
    const getItems = async () => {
-      const result = await axios.get('https://api.publicapis.org/entries')
+      const result = await axios.get(`https://api.publicapis.org/entries/${categoryId}`)
      setItems(result.data.entries)
      console.log("result.entries", result.data.entries);
    }
    getItems()
  }, [])

logancodemaker 的回答几乎是正确的,但缺少一些东西。

基本上您需要将类别发送到项目组件才能按类别过滤。

1-) 必须在 App.js 中更新项目路线以接受 url 参数。

<Route path="/items/:category" element={<Items />}/>

2-) 我们使用 Categories.js 中 react-router-dom 包中的 Link 组件来动态发送类别 url 参数。

<Link to={`/items/${category}`} >{category}</Link>

3-) 在 Items.js 中,我们按给定的类别名称过滤产品。

    import { useParams } from 'react-router-dom';
    
    const {category} = useParams(); 
    
    useEffect(() => {
        const getItems = async () => {
            const result = await axios.get('https://api.publicapis.org/entries');

            const allItems = result.data.entries;
            const categoryItems = allItems.filter(item => item.Category === category);
            setItems(categoryItems)
        }
        getItems()
    }, [category])