Reactjs 是否有更好的方法根据数据类型从同一组件中的API获取不同的数据?

Reactjs 是否有更好的方法根据数据类型从同一组件中的API获取不同的数据?,reactjs,Reactjs,我有一个包含多个部分的主页,我希望每个部分都能获得不同的数据,比如一个是“流行食谱”,另一个是“新食谱”。因此,我在useeffect中为此写了一个switch语句,但我觉得这不是“最好的方式” Home.js: import React from "react"; import { Container } from "@chakra-ui/react"; import Section from "./Section"; const

我有一个包含多个部分的主页,我希望每个部分都能获得不同的数据,比如一个是“流行食谱”,另一个是“新食谱”。因此,我在useeffect中为此写了一个switch语句,但我觉得这不是“最好的方式”

Home.js:

import React from "react";
import { Container } from "@chakra-ui/react";
import Section from "./Section";

const sections = [
  {
    name: "Popular Recipes",
  },
  { name: "New Recipes" },
];

function Home() {
  return (
    <Container maxWidth="full">
      {sections.map((section, i) => (
        <Section key={i} name={section.name} />
      ))}
    </Container>
  );
}

export default Home;
从“React”导入React;
从“@chakra ui/react”导入{Container}”;
从“/Section”导入节;
常数段=[
{
名称:“流行食谱”,
},
{name:“新配方”},
];
函数Home(){
返回(
{sections.map((section,i)=>(
))}
);
}
导出默认主页;
第6.js节:

import React, { useEffect, useState } from "react";
import { Text, Flex, Box, Spacer, SimpleGrid, Heading } from "@chakra-ui/react";
import { getAllRecipes } from "../api";
import Recipe from "../common/Recipe";

function Section(props) {
  const [recipes, setRecipes] = useState([]);
  const [error, setError] = useState("");
  useEffect(() => {
    switch (props.name) {
      case "Popular Recipes":
        getAllRecipes()
          .then((data) => {
            setRecipes(data);
          })
          .catch((error) => setError(error.response.data.error));
    }
  }, []);
  return (
    <Box marginBottom="10">
      <Heading as="h2" marginBottom="5" fontSize="xl" fontWeight="hairline">
        {props.name}
      </Heading>
      <SimpleGrid minChildWidth="250px" columns={3} spacing={6}>
        {error ? (
          <Text>{error}</Text>
        ) : (
          recipes?.map((recipe) => {
            return <Recipe key={recipe._id} recipe={recipe} />;
          })
        )}
      </SimpleGrid>
    </Box>
  );
}

export default Section;
import React,{useffect,useState}来自“React”;
从“@chakra ui/react”导入{Text,Flex,Box,Spacer,SimpleGrid,Heading}”;
从“./api”导入{getAllRecipes};
从“./common/Recipe”导入配方;
功能部分(道具){
const[recipes,setRecipes]=useState([]);
const[error,setError]=useState(“”);
useffect(()=>{
开关(道具名称){
案例“流行食谱”:
getAllRecipes()
。然后((数据)=>{
设置配方(数据);
})
.catch((error)=>setError(error.response.data.error));
}
}, []);
返回(
{props.name}
{错误(
{错误}
) : (
配方?.map((配方)=>{
返回;
})
)}
);
}
导出默认部分;

不依赖于
道具.name
,只需让您的
部分
组件接受一个
getRecipes
道具,并在父组件中显式传递它即可。这将使
name
与实际实现脱钩,因此将
最新配方
更改为
最新帖子
(或其他)不会破坏您的应用程序

//querys.js-----
export const getPopularRecipes=()=>fetch('/recipes/popular')。然后(res=>res.json());
export const getLatestRecipes=()=>fetch('/recipes/latest')。然后(res=>res.json());
//Section.js-----
功能部分(道具){
// ...
useffect(()=>{
props.getRecipes()
.然后(数据=>setRecipes(数据))
.catch(error=>setError(error.response.data.error));
}, []);
// ...
}
//Home.js-----
从“/queries”导入{getPopularRecipes,getLatestRecipes};
函数Home(){
返回(
);
}
或者,如果获取配方的逻辑相同(例如,只有API路径不同),则可以让
部分
组件接受一个
recipeType
属性(或类似属性)

//Section.js-----
功能部分(道具){
// ...
useffect(()=>{
获取(`/recipes/${props.recipeType}`)
.then(res=>res.json())
.然后(数据=>setRecipes(数据))
.catch(error=>setError(error.response.data.error));
}, []);
// ...
}
//Home.js-----
从“/queries”导入{getPopularRecipes,getLatestRecipes};
函数Home(){
返回(
);
}

不管怎样,将您的网络实现与您的
名称
分离,您应该能够适应未来的重构。

最好在主组件中获取不同种类的配方,并只将相关数据传递给每个部分组件。这些解决方案的唯一问题是,如果我有1000个部分,我必须编写所有的部分他们。我试图通过循环遍历一组截面对象并渲染截面组件来防止这种情况。也许我应该将api函数添加到每个对象中。您必须为
getRecipes
recipePath
指定值,不管您是在每个
部分
中还是在问题中使用的
部分
对象中一次指定一个值。您只需使用类似于
const sections=[{name:'Popular Recipes',recipePath:'Popular'},{name:'Latest Recipes',recipePath:'Latest'},…]