我需要执行fetch API调用,该调用返回一个URL,对返回的URL进行处理,然后在60秒后刷新该URL。如果没有钩子,我可以轻松实现这一目标,但是我想要一个钩子解决方案。
重要:我不想将其重构为多个组件,也不希望为计时器或API调用创建自定义钩子。
EDIT :问题是-这是在hooks环境中处理计时器的正确方法吗?有更好的方法吗?
import React, { useState, useEffect } from 'react'
import { post } from 'utils/requests'
const FetchUrl = ({ id }) => {
const [url, setUrl] = useState('')
let [count, setCount] = useState(0)
const tick = () => {
let newCount = count < 60 ? count + 1 : 0
setCount(newCount)
}
useEffect(() => {
const timer = setInterval(() => tick(), 1000)
if (count === 0) {
post('/api/return-url/', { id: [id] })
.then(res => {
if (res && res.content) {
setUrl(res.content.url)
}
})
}
return () => clearInterval(timer)
})
return url ? (
<span className="btn sm">
<a href={url} target="_blank" rel="noopener noreferrer">go</a>
</span>
) : null
}
export default FetchUrl
答案 0 :(得分:1)
看看是否适合您。
我将其分为2 useEffect()
。在第一个渲染后运行(类似于componentDidMount
)来设置计时器。并根据计数值进行API调用。
注意:我使用ref
只是为了区分一个API调用和另一个API调用,并为其添加一个数字。
请参见下面的代码段
:
const FetchUrl = ({ id }) => {
const [url, setUrl] = React.useState('');
const [count, setCount] = React.useState(0);
const someRef = React.useRef(0);
const tick = () => {
//let newCount = count < 60 ? count + 1 : 0
setCount((prevState) => prevState < 60 ? prevState +1 : 0);
}
function mockAPI() {
return new Promise((resolve,request) => {
someRef.current = someRef.current + 1;
setTimeout(()=>resolve('newData from API call ' + someRef.current),1000);
});
}
React.useEffect(() => {
const timer = setInterval(() => tick(), 100);
return () => clearInterval(timer);
});
React.useEffect(() => {
if (count === 0) {
/*post('/api/return-url/', { id: [id] })
.then(res => {
if (res && res.content) {
setUrl(res.content.url)
}
})
*/
mockAPI().then((data) => setUrl(data));
}
},[count]);
return url ? (
<span className="btn sm">
<div>{count}</div>
<a href={url} target="_blank" rel="noopener noreferrer">{url}</a>
</span>
) : null
}
ReactDOM.render(<FetchUrl/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>