gpt4 book ai didi

reactjs - 返回的 React Custom Hook set 函数不是函数

转载 作者:行者123 更新时间:2023-12-04 13:36:33 26 4
gpt4 key购买 nike

因此,我构建了一个自定义钩子(Hook)来从 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 比较陌生,所以任何反馈都会有很大帮助。

谢谢。

编辑:

为了提供更多上下文,我在我的组件片段中添加了更多代码。我尝试更新 isLoading状态来自 setInterval .但我也尝试过 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

最佳答案

像这样使用它:

更新:根据 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>
);
}

这是一个 codesandbox例子。

关于reactjs - 返回的 React Custom Hook set 函数不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61670122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com