useEffect 和 setState 带钩子函数

useEffect and setState with hook function

我想尝试使用 react 并适当地使用 useEffect 有效地获取数据。

目前,数据获取是不断发生的,而不是只需要一次,并且在有日期期间的输入时发生变化(调用不同的数据)。

组件是这样的,

export default function Analytics() {

  const {
    sentimentData,
    expressionsData,
    overall,
    handleChange,
    startDate,
    endDate,
    sentimentStatistical,
  } = useAnalytics();

  

  return (

UseAnalytics 是另一个专门用来取数据的组件,基本上就是一系列的取数据。

export default function useAnalytics() {
....
const { data: sentimentData } = useSWR(
        `dashboard/sentiment/get-sentiment-timefilter?startTime=${startDate}&endTime=${endDate}`,
        fetchSentiment
      );
      ....
      return {
        sentimentData,
        expressionsData,
        overall,
        handleChange,
        setDateRange,
        sentimentStatistical,
        startDate,
        endDate,
      };
    }

提前致谢,

apirequest是这样的,

export async function apiRequest(path, method = "GET", data) {
  const accessToken = firebase.auth().currentUser
    ? await firebase.auth().currentUser.getIdToken()
    : undefined;
    //this is a workaround due to the backend responses not being built for this util.
  if (path == "dashboard/get-settings") {
    return fetch(`/api/${path}`, {
      method,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`,
      },
      body: data ? JSON.stringify(data) : undefined,
    })
      .then((response) => response.json())
      .then((response) => {
        if (response.error === "error") {
          throw new CustomError(response.code, response.messages);
        } else {
          return response;
        }
      });
  }
  return fetch(`/api/${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
    body: data ? JSON.stringify(data) : undefined,
  })
    .then((response) => response.json())
    .then((response) => {
      if (response.status === "error") {
        // Automatically signout user if accessToken is no longer valid
        if (response.code === "auth/invalid-user-token") {
          firebase.auth().signOut();
        }

        throw new CustomError(response.code, response.message);
      } else {
        return response.data;
      }
    });
}

我认为在这里使用 useEffect 是正确的做法。即,

useEffect(()=>{
  // this callback function gets called when there is some change in the 
  // state variable (present in the dependency array)
},[state variable])

我对如何正确更新常量感到困惑,像这样的方法似乎是一种方法,但不确定如何使用 useEffect 正确更新这些变量,或者我是否应该在 useAnalytics 中执行此操作?

const [analytics, setAnalytics] = useState({
    sentimentData: {},
    expressionsData: {},
    overall: {},
    handleChange: () => {},
    startDate: '',
    endDate: '',
    sentimentStatistical:{},
  });

  useEffect(()=>{
    // this callback function gets called when there is some change in the 
    // state variable (present in the dependency array)
  },[state variable])
  const {
    sentimentData,
    expressionsData,
    overall,
    handleChange,
    startDate,
    endDate,
    sentimentStatistical,
  } = useAnalytics();

实现SWR是一个hook,需要使用SWR文档:P

您必须将请求的信息存储在自定义挂钩内的状态中。然后你可以在任何你想要的地方使用这个钩子。这应该有效。

定义自定义挂钩

const useAnalitycs  = () => {
  const [analytics, setAnalytics] = useState({
    sentimentData: {},
    expressionsData: {},
    overall: {},
    startDate: '',
    endDate: '',
    sentimentStatistical:{},
  });

  const handleChange = () => {
    /* */
  };

  useEffect(() => {
    const fetchData = async () => {
      // const response = await apiCall();
      // setAnalytics(...)
    };
    fetchData();
  }, []); // called once

  return {
    ...analytics,
    handleChange
  };
};

使用 useAnalytics 挂钩

const ComponentConsumerA = () => {
  /* 
  const { state/methods you need } = useAnalytics()

  ...
  */
};

const ComponentConsumerB = () => {
  /* 
  const { state/methods you need } = useAnalytics()

  ...
  */
};