React js 在页面加载时调用 api

问题描述 投票:0回答:2

我正在学习React js,我使用下面的数据代码来绑定从API接收的值。我正在使用

MUI Datatable
绑定数据,一切正常。我的问题是,当我运行 React js 应用程序时,它首先渲染空的 mui 数据表,然后加载数据。无论如何,我可以在主页加载时先调用 api onpageload 吗?

function GetEmployeeList() {
  const [empList, setEmpList] = useState([]);
  const getEmployeeList = () => {
    axios.get(configData.SERVER_URL + "/api/getEmployeeList").then((res) => {
      const Employee = res.data;
      setEmpList(Employee);
    });
  };
  useEffect(() => {
    const interval = setInterval(() => getEmployeeList(), 10000);
    return () => {
      clearInterval(interval);
    };
  }, []);
  return EmployeeListTable(empList);
}

function EmployeeListTable(value) {
  if (
    typeof value == "undefined" ||
    value == null ||
    value.length == null ||
    value.length < 0
  ) {
    return <div></div>;
  }
  const columns = [
   { label: "Employee ID", name: "id" },
   { label: "EmpoyeeName", name: "name" },
   { label: "Address", name: "address" },
   { label: "Number", name: "number" },
  
  ];

  const data = value.map((item) => {
    return [
      item.id
      item.name,
      item.address,
      item.number,
    ];
  });

  const options = {
    caseSensitive: true,
    responsive: "standard",
    selectableRows: "none",
  };

  return (
    <MUIDataTable
      title={"Employee"}
      data={data}
      columns={columns}
      options={options}
    />
  );
}
javascript node.js reactjs react-hooks
2个回答
5
投票

如果您只想在有一些数据时渲染 UI,那么您可以这样做:

return (
    data.length > 0 && 
      <MUIDataTable
        title={"Employee"}
        data={data}
        columns={columns}
        options={options}
      />
  );

编辑:

const HomeComponent = () => {
  const [data, setData] = React.useState([])

  useEffect(() => {
    axios
      .get(configData.SERVER_URL + "/api/getEmployeeList")
      .then((res) => {
        setData(res.data)
      })
  })

  return (
    {data.length > 0 && 
      <EmployeeComponent data={data} />
    }
  )
}

0
投票
useEffect(() => {
        getFilterList()
    }, [])


const getFilterList = async () => {
        const response = await getCall(HANDSET_USER_FILTER_DATA, null, props?.user?.access_token)
        if (response?.code === 200) {
            setFormData((prev) => ({
                ...prev,
                filter: { ...prev.filter, list: { ...prev.filter?.list, ...response?.data } }
            }))
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.