React js 在页面加载时调用 api
2021-05-24
45099
我正在学习 React js,我正在使用下面的数据代码来绑定从 API 接收的值。我正在使用
MUI Datatable
来绑定数据,一切正常。我的问题是当我运行 react js 应用程序时,它首先渲染空的 mui datatable 表,然后加载数据。有没有什么办法可以在主页加载时首先调用 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}
/>
);
}
1个回答
如果您只想在有数据时呈现 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} />
}
)
}
Delice
2021-05-24