haw*_*awx 5 reactjs react-native react-component react-context react-functional-component
我有以下反应类组件每 10 秒调用一次 API。它的作品没有问题。
class Alerts extends Component {
constructor() {
this.state = {
alerts: {},
}
}
componentDidMount() {
this.getAlerts()
this.timerId = setInterval(() => this.getAlerts(), 10000)
}
componentWillUnmount() {
clearInterval(this.timerId)
}
getAlerts() {
fetch(this.getEndpoint('api/alerts/all"))
.then(result => result.json())
.then(result => this.setState({ alerts: result }))
}
render() {
return (
<>
<ListAlerts alerts={this.state.alerts} />
</>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将其转换为反应功能组件。这是我迄今为止的尝试。
const Alerts = () => {
const [alerts, setAlerts] = useState([])
useEffect(() => {
getAlerts()
setInterval(() => getAlerts(), 10000)
}, [])
getAlerts() {
fetch(this.getEndpoint('api/alerts/all"))
.then(result => result.json())
.then(result => setAlerts(result)
}
return (
<>
<ListAlerts alerts={alerts} />
</>
)
}
Run Code Online (Sandbox Code Playgroud)
请有人帮我完成这个例子吗?useEffect 是正确的用法还是有更好的选择?
任何帮助,将不胜感激
azu*_*ndo 10
这里的一个问题是this.getEndpoint
无法从功能组件中工作。似乎原始Alerts
类组件缺少一些代码,因为它必须在某处实现。
另一个问题是间隔没有被清理——你应该从效果体返回一个清理函数来清除计时器。
最后,没有理由getAlerts
在每次渲染时重新定义,在效果体内部定义一次会更好。
在清理了一些缺失的括号等之后,我的最终实现看起来像:
function getEndpoint(path) {
return ...; // finish implementing this
}
const Alerts = () => {
const [alerts, setAlerts] = useState([])
useEffect(() => {
function getAlerts() {
fetch(getEndpoint('api/alerts/all'))
.then(result => result.json())
.then(result => setAlerts(result))
}
getAlerts()
const interval = setInterval(() => getAlerts(), 10000)
return () => {
clearInterval(interval);
}
}, [])
return (
<>
<ListAlerts alerts={alerts} />
</>
)
}
Run Code Online (Sandbox Code Playgroud)
我找到了 Dan Abramov 的这个博客,它解释了useInterval
解决这个问题的钩子的想法。你可以这样使用它:
function Counter() {
useInterval(() => {
callMyApi()
}, 1000);
}
Run Code Online (Sandbox Code Playgroud)
并以useInterval
这种方式声明钩子:
import React, { useState, useEffect, useRef } from 'react';
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
Run Code Online (Sandbox Code Playgroud)
希望它可以帮助某人!
归档时间: |
|
查看次数: |
6393 次 |
最近记录: |