首页 > 解决方案 > React Custom Hook set 返回的函数不是函数

问题描述

因此,我构建了一个自定义钩子来从 api 获取数据。这是代码:

export const useLambdaApi = () => {
  const [data, setData] = useState()
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    const fetchData = async () => { ... }
    fetchData();
  },[isLoading]);

  return [data, setIsLoading];
}

在组件中,我需要我做的数据:

export default function Comp (props) {
  const [data, setIsLoading] = useLambdaApi()

  useEffect(() => {
    const interval = setInterval(() => {
      setIsLoading(true)
      console.log(Date())
    }, 10000);
    return () => {
      window.clearInterval(interval); // clear the interval in the cleanup function
    };
  },[data]);
  return( ... )
}

但我得到一个类型错误:TypeError: setIsLoading is not a function

我知道这一定很愚蠢,但我对 React 还比较陌生,所以任何反馈都会有很大帮助。

谢谢。


编辑:

为了提供更多上下文,我在我的组件片段中添加了更多代码。我尝试isLoadingsetInterval. 但我也确实尝试过useEffect没有间隔,并且在 useEffect 之外......

这是堆栈跟踪:

PatientBoard.js:26 Uncaught TypeError: setIsLoading is not a function
    at PatientBoard.js:26
(anonymous) @ PatientBoard.js:26
setInterval (async)
(anonymous) @ PatientBoard.js:25
commitHookEffectList @ react-dom.development.js:21100
commitPassiveHookEffects @ react-dom.development.js:21133
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:466
flushPassiveEffectsImpl @ react-dom.development.js:24223
unstable_runWithPriority @ scheduler.development.js:676
runWithPriority$2 @ react-dom.development.js:11855
flushPassiveEffects @ react-dom.development.js:24194
(anonymous) @ react-dom.development.js:23755
scheduler_flushTaskAtPriority_Normal @ scheduler.development.js:451
flushTask @ scheduler.development.js:504
flushWork @ scheduler.development.js:637
performWorkUntilDeadline @ scheduler.development.js:238

标签: reactjsreact-hooksuse-state

解决方案


像这样使用它:

更新:根据 URL 更改触发重新获取:

import React, { useEffect, useState } from "react";

// Passing URL as a parameter
export const useLambdaApi = (url) => {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(url);
      const data = await response.json();

      // Set stats
      setIsLoading(false);
      setData(data);
    };
    fetchData();

  // Passing URL as a dependency
  }, [url]);

  // Return 'isLoading' not the 'setIsLoading' function
  return [data, isLoading];
};

// Using Hook into your component
export default function App() {
    // State will be changed if URL changes
    const [data, isLoading] = useLambdaApi('Your URL');

  // Loading indicator
  if (isLoading) return <div>Loading..</div>;

  // Return data when isLoading = false
  return (
    <div className="App">
      // Use data..
    </div>
  );
}

这是一个代码框示例。


推荐阅读