如何在 React 中进行条件渲染

How to do conditional rendering in React

我正在尝试通过填充本地 JSON 文件中的数据来呈现图表。初始渲染不会填充数组,因此我向图表组件添加了条件渲染。但是我在某处出错了,在添加条件后图表组件不呈现。我哪里错了?

Screen grab of the empty array at the time of rendering

对应代码:

import BarChart from "./BarChart";
import { styled } from "@mui/material/styles";

import axios from "axios";

const drawerWidth = 340;
const open = true;

const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
  ({ theme, open }) => ({
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: `-${drawerWidth}px`,
    ...(open && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen,
      }),
      marginLeft: 0,
    }),
  })
);

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
  justifyContent: "flex-end",
}));

export function Test() {
  const [candidate, setCandidate] = useState([]);
  useEffect(() => {
    axios
      .get("./data.json")
      .then((res) => setCandidate(res.data))
      .catch((err) => console.log(err));
  }, []);
  
  //role
  let dataMap = new Map();
  let roleCategoriesArray = [];
  let roleCountArray = [];
  
  for (let attribute of candidate) {
    if (!dataMap.has(attribute.band)) {
      dataMap.set(attribute.band, 1);
    } else {
      dataMap.set(attribute.band, dataMap.get(attribute.band) + 1);
    }
  }

  for (let [key, value] of dataMap) {
    roleCategoriesArray = [...roleCategoriesArray, key];
    roleCountArray = [...roleCountArray, value];
  }
  //spoc 

  dataMap = new Map();
  let spocCategoriesArray = [];
  let spocCountArray = [];
  for (let attribute of candidate) {
    if (!dataMap.has(attribute.spoc)) {
      dataMap.set(attribute.spoc, 1);
    } else {
      dataMap.set(attribute.spoc, dataMap.get(attribute.spoc) + 1);
    }
  }

  for (let [key, value] of dataMap) {
    spocCategoriesArray = [...spocCategoriesArray, key];
    spocCountArray = [...spocCountArray, value];
  }

  const roleData = {
    count: roleCountArray,
    categories: roleCategoriesArray,
    titleText: "Role coverage",
    color: "#CB5757",
  };

  console.log(roleData);

  const spocData = {
    count: spocCountArray,
    categories: spocCategoriesArray,
    titleText: "SPOC",
    color: "#CF9152",
  };

  return (
    <Main open={open}>
      <DrawerHeader />
      <div style={{ marginTop: "100px", display: "flex", flexDirection: "row", flexWrap: "wrap",rowGap: "250px", coulmnGap:"100px"}}>
      {roleData.count>0 && <BarChart data={roleData} style={{ padding: "200px" }} />}
        <br />
        <hr />
        <br />
        {spocData.count>0 && <BarChart data={spocData} style={{ padding: "200px" }} />}   
      </div>
    </Main>
  );
}

如果要使用数组长度作为判断依据,请尝试将roleData.count > 0修改为roleData.count.length > 0

...
return (
    <Main open={open}>
      <DrawerHeader />
      <div style={{ marginTop: "100px", display: "flex", flexDirection: "row", flexWrap: "wrap",rowGap: "250px", coulmnGap:"100px"}}>
      {/* ==== Here ==== */}
      {roleData.count.length > 0 && <BarChart data={roleData} style={{ padding: "200px" }} />}
        <br />
        <hr />
        <br />
        {/* ==== And Here ==== */}
        {spocData.count.length > 0 && <BarChart data={spocData} style={{ padding: "200px" }} />}   
      </div>
    </Main>
  );