【问题标题】:how to render react functional component after interval如何在间隔后渲染反应功能组件
【发布时间】:2022-01-06 13:10:16
【问题描述】:
useEffect(() => {
const url = `https://......com/..../${id}`;
fetch(url)
.then((res) => res.json())
.then((data) => {
console.log(serviceDetail);
setServiceDetail(data);
});
注意:我希望它每隔 5 秒渲染一次。(或多或少)
【问题讨论】:
标签:
reactjs
react-hooks
functional-programming
render
intervals
【解决方案1】:
试试这个有帮助的代码
function App() {
const [serviceDetail, setServiceDetail] = useState(0);
const handleApiCall = () => {
const url = 'https://......com/..../${id}';
fetch(url).then((res) => res.json()).then((data) => {
console.log(serviceDetail); setServiceDetail(data);
});
}
useEffect(() => {
handleApiCall(); //for call api init time
const interval = setInterval(() => {
handleApiCall(); // call api after 5 seconds
}, 5000);
return () => clearInterval(interval); // clear interval after component unmounts.
});
return (
<div>
</div>
);
}
export default App;
【解决方案2】:
(当前)接受的答案遗漏了一个重要细节。当组件卸载时,间隔将继续运行。要阻止它,您需要clearInterval。另一个错误是 useEffect 在没有依赖关系的情况下被调用。这里我们使用useCallback 来生成一个仅在id 更新时才会更新的函数。回调和id 都作为依赖项传递给useEffect -
const [data, setData] = useState(...)
const update = useCallback(id =>
fetch(`http://.../${id}/`)
.then(r => r.json())
.then(setData),
[id]
)
useEffect(() => {
const t = setInterval(_ => update(id), 5000)
return () => clearInterval(t)
}, [update, id])
在related Q&A 中,我们引入了一个自定义的useInterval 钩子,使组件可以轻松地处理基于间隔的状态。有关功能齐全的代码演示,请参阅帖子。