javascript - 在反应组件中使用 setInterval 重复函数调用的一种替代方法?
问题描述
我有 3 个函数在我的反应组件中重复运行。他们工作正常,但我想清理代码,以便我可以重复调用该函数,而无需初始化然后设置间隔。
有没有办法在没有componentDidMount中的初始函数调用的情况下调用函数并设置间隔?
export class CryptoData extends Component {
static propTypes = {
pair: PropTypes.string.isRequired
}
state = {
price: null,
change1Hr: null,
change24Hr: null
}
getAsync = (func, state) => {
func(this.props.pair).then(res => {
this.setState({ [state]: res })
}).catch(err => console.log(err))
}
componentDidMount() {
this.getAsync(getPrice, "price")
this.getAsync(get1HrChange, "change1Hr")
this.getAsync(get24HrChange, "change24Hr") // <- Remove fist 3 lines?
this.interval = setInterval(() => this.getAsync(getPrice, "price"), 15000)
this.interval = setInterval(() => this.getAsync(get1HrChange, "change1Hr"), 30000);
this.interval = setInterval(() => this.getAsync(get24HrChange, "change24Hr"), 20000)
}
componentWillUnmount() {
clearInterval(this.interval);
}
解决方案
使用钩子,您可以将获取和更新值的所有逻辑抽象到一个钩子中:
function useUpdatedData(fetcher, interval) {
const [value, setValue] = useState(null);
useEffect(() => {
let timer;
async function update() {
setValue(await fetcher());
timer = setTimeout(update, interval);
}
update();
return () => clearTimeout(timer);
}, [fetcher]);
return value;
}
function CryptoData() {
const price = useUpdatedData(getPrice, 1500);
//...
}
推荐阅读
- r - Filtering Using the Results of Grouping
- c# - How to use Github API on a ASP.NET MVC app?
- javascript - 从两个订阅中获取一个订阅
- inheritance - F# inheritance with multiple constructors syntax
- java - How can i sort albums from songs?
- android - Floating Action Button is translucent for some reason
- css - Highlight label when the field is focused
- react-native - 如何在渲染方法之外调用 redux 操作
- mysql - MySQL 5.5.57 数据库设计建议请求数据库中的“用户”表
- javascript - 如果选中复选框,如何在提交后显示输入类型文本