首页 > 解决方案 > 使用反应 useEffect 钩子

问题描述

我正在使用 React useEffect 挂钩来获取数据并显示加载指示器,但我的加载不起作用。

下面是 useEffect Hook 代码:

useEffect(() => {
  fetchEvents();
}, []);

fetchEvents功能代码:

const fetchEvents = () => {
  setLoading(true);
  const requestBody = {
    query: `
              query {
                events {
                  _id
                  title
                  description
                  price
                  date
                  creator {
                    _id
                    email
                  }
                }
              }
            `
  };

  fetch("http://localhost:5000/graphql", {
      headers: {
        "Content-Type": "application/json"
      },
      method: "POST",
      body: JSON.stringify(requestBody)
    })
    .then(res => {
      if (res.status !== 200 && res.status !== 201) {
        throw new Error("Failed");
      }
      return res.json();
    })
    .then(resData => {
      const events = resData.data.events;
      setEvents(events);
      setLoading(false);
    })
    .catch(err => {
      console.log(err);
      setLoading(false);
    });
};

标签: reactjs

解决方案


您应该提供更多信息,但这里有一个示例:

import React, { useState, useEffect } from 'react';
import { Spinner } from 'react-bootstrap';

const MyComponent = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState([]);

  useEffect(() => {
    setIsLoading(true);
    fetch('/data/endpoint')
      .then((res) => res.json)
      .then((response) => {
        setData([...response]);
        setIsLoading(false);
      });
  }, []);

  return isLoading ? (
    <Spinner />
  ) : (
    <ol>
      data.map(items => <li>{items.label}</li>);
    </ol>
  );
};

推荐阅读