reactjs - 如何在 Reactjs 上运行一个函数并每 5 秒更改一次内容
问题描述
您好,我想知道你们如何在 React js 上每 5 秒运行一个函数
这是代码:
function Home() {
const [quotes,setQuotes] = useState([])
const getQuotes = ()=>{
axios.get('https://api.kanye.rest')
.then(res=>{
const quotes = res.data.quote
setQuotes(quotes)
})
}
useEffect(()=>{
getQuotes()
},[])
return (
<div className="home-container">
<p className="pcolor">Here's a random quotes from Kanye:</p>
<p>{quotes}</p>
</div>
)}
我想知道如何每 5 秒获取一次数据,所以我会在 jsx 中自动更新。是的,每次我们请求时,kanye api 都会给我们一个随机报价。
解决方案
// Use a ref to keep track of a stateful value that doesn't affect rendering,
// the `setInterval` ID in this case.
const intervalRef = useRef();
const [quotes, setQuotes] = useState([])
useEffect(() => {
const getQuotes = () => {
axios.get('https://api.kanye.rest')
.then(res=>{
const quotes = res.data.quote
setQuotes(quotes)
})
}
intervalRef.current = setInterval(getQuotes, 5000);
// Clear the interval when this hook/component unmounts so it doesn't keep
// running when this component is gone.
return () => {
clearInterval(intervalRef.current);
}
}, [])
推荐阅读
- mysql - MySql 表列自动添加现有列
- javascript - Angular svg 作为显示为文本的组件的模板
- powershell - [Class]::New() 导致控制台出现空行
- python - 使用 OpenCV 从背景中裁剪图像(条带提取)
- computer-vision - 读取 mjsynth 数据集图像的问题
- delphi - Delphi 5 仅对整个单词使用 Pos / PosIgnoreCase
- linear-programming - 如何在 C++ 中使用 conshdlr 获取已添加到 SCIP 的切割数量和实际切割
- python-3.x - 如何在列中计算连续 1 并获得每组的最大计数
- azure - ApplicationInsights 不考虑 json 配置的日志级别
- json - 世界银行 COVID-19 API(不完整的 JSON)