反应如何将 setInterval 与 useEfecct 和 axios 请求一起使用
React how to use setInterval with useEfecct and axios request
在哪里我必须使用 setInterval 每秒获取一次?
当我尝试它时,我收到此错误 Uncaught SyntaxError: Unexpected identifier
useEffect(() => {
const getHistory = async () => {
const res = await axios.get('/api/payment', {
headers: { Authorization: token },
});
setHistory(res.data);
};
getHistory();
}, [token, delivered]);
您可以为此使用 swr
,并且不仅可以受益于 built-in 间隔重新验证,还可以受益于缓存和重复数据删除。
import useSWR from 'swr'
// You can use axios if you want
const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR('/api/payment', fetcher, { refreshInterval: 1000 })
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>Look at all this data: {data.someProperty}</div>
在哪里我必须使用 setInterval 每秒获取一次? 当我尝试它时,我收到此错误 Uncaught SyntaxError: Unexpected identifier
useEffect(() => {
const getHistory = async () => {
const res = await axios.get('/api/payment', {
headers: { Authorization: token },
});
setHistory(res.data);
};
getHistory();
}, [token, delivered]);
您可以为此使用 swr
,并且不仅可以受益于 built-in 间隔重新验证,还可以受益于缓存和重复数据删除。
import useSWR from 'swr'
// You can use axios if you want
const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR('/api/payment', fetcher, { refreshInterval: 1000 })
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>Look at all this data: {data.someProperty}</div>