首页 > 解决方案 > ReactJS - 传递参数以获取请求

问题描述

以下是显示所有类别的 React 组件,在此路由 http://localhost:3000/categories

import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
// Material-UI core
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
// Local Components
import BodyWrapper from 'components/bodyWrapper';
import Spinner from 'components/progressAnimations/spinner';
import CategoryCard from 'components/categoryCard';

import { CARD1, CARD2, CARD3 } from '../../constants'; // images
import { useStyles } from './style';

function Categories(props) {
    const classes = useStyles();
    const loading = useSelector(state => state.categories.isLoading);
    const categories = useSelector(state => state.categories.categories);

    return (
        <BodyWrapper spacing = "40px" containerWidth = "lg">
            <h2>Categories</h2>
            <Grid container spacing={4}>
                {
                    !loading ?
                    categories.data[0].documents.map((category, index) => (
                        <Grid key={index} item xs={6} md={4} lg={3} >
                            <Link to = {`/categories/${category.name}`} style={{ textDecoration: "none" }}>
                            <CategoryCard image={ category.imageUrl || CARD2 } title={ category.name } />
                            </Link>
                        </Grid>
                    )) : (
                        <div className = { classes.spinner }>
                            <Spinner />
                        </div>
                    )
                }
            </Grid>
        </BodyWrapper>
    );
}

export default Categories;

当单击特定类别时,我想加载一个新组件并创建一个 GET 请求到具有类别 ID 的服务器以加载与类别相关的所有数据。

http://localhost:3000/categories/Photographers

这是 API URL,我想通过 GET 请求发送“类别 ID”。

{{SERVER}}/api/vendor/getAll?page=1&limit=10&categories=5fdf4d9db1ecf930cd09331b

我想知道将类别 ID 传递给下一个组件的最佳方法。

标签: reactjsreact-reduxreact-routermern

解决方案


你可以这样:

import React, { useEffect, useState } from "react";
import axios from "axios";

const Categories = (props) => {
  // we get something from Redux
  const categories = ["a", "b", "c", "d", "e", "f"];
  const [currentCategory, setCurrentCategory] = useState(null);

  return props.loading ? (
    "Loading..."
  ) : (
    <div>
      <h2>Select category</h2>
      {categories.map((category) => (
        <div key={category} onClick={() => setCurrentCategory(category)}>
          Category: {category}
        </div>
      ))}
      <div>current category is {String(currentCategory)}</div>
      {currentCategory && <Category id={currentCategory} />}
    </div>
  );
};

const Category = ({ id }) => {
  const [data, setData] = useState(null);

  const url = "https://someurl.com";

  useEffect(() => {
    const fetchData = async () => {
      const dataFromServer = await axios.get(`${url}/${id}`);
      setData(dataFromServer);
    };
    fetchData();
  }, [id]);

  return data ? (
    <div>Render data here: {data}</div>
  ) : (
    `Loading category ${id}...`
  );
};

const App = () => {
  return (
    <div>
      <Categories />
    </div>
  );
};

export default App;

推荐阅读