因此,我建立了一个自定义钩子以从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: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
像这样使用它:
import React, { useEffect, useState } from "react";
export const useLambdaApi = () => {
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(...);
const data = await response.json();
// Set stats
setIsLoading(false);
setData(data);
};
fetchData();
}, []);
// Return 'isLoading' not the 'setIsLoading' function
return [data, isLoading];
};
// Using Hook into your component
export default function App() {
const [data, isLoading] = useLambdaApi();
// Loading indicator
if (isLoading) return <div>Loading..</div>;
// Return data when isLoading = false
return (
<div className="App">
// Use data..
</div>
);
}
这里是codesandbox示例。