【问题标题】:React js call api on page load在页面加载时反应 js 调用 api
【发布时间】:2021-05-24 10:51:06
【问题描述】:

我正在学习 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


    【解决方案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} />
        }
      )
    }
    

    【讨论】:

    • 这意味着用户必须等到数据被绑定,否则它会清空这很好,让我们考虑2个页面,一个是home page,另一个是Employee页面。当我运行 react js 时,它首先加载主页所以有什么方法可以在主页加载时调用 ````Employee``` 页面 API 方法
    • 如果我理解正确 - 你想在 Employee 页面甚至渲染之前加载主页中的数据,对吗?如果是这样 - 你应该在 Home 组件中有一个 useEffect 来获取数据,然后将数据作为道具提供给 Employee 组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多