React-Native:加载组件时在后台运行一个函数

React-Native: run a function in background while component is loaded

本文关键字:函数 一个 运行 后台 加载 组件 React-Native      更新时间:2023-09-26

在一个组件中,当listview和其他东西被加载时

是否可以在后台运行一个函数,每隔几分钟重新加载listview数据?

如果是,当用户离开组件(转到另一个选项卡,iOS),功能会停止吗?

您可以通过在componentDidMount中添加setInterval并在componentWillUnmount中清除它来实现。

let interval;
class HelloWorld extends Component {
  componentDidMount() {
    interval = setInterval(() => {
        // do what you want here.
    }, 10000);
  }
  componentWillUnmount() {
    clearInterval(interval);
  }
  render() {
    return (
      <Text>Hello world!</Text>
    );
  }
}