代码之家  ›  专栏  ›  技术社区  ›  ishandutta2007

如何将此刷新操作调用为连续后台作业

  •  1
  • ishandutta2007  · 技术社区  · 7 年前

    这是Electron应用程序的一部分,按UI上的刷新按钮时调用此操作。我想让它自动刷新。我该怎么做?

    组件/计数器.js:

    export default class Counter extends Component<Props> {
      props: Props;
    
      render() {
        const {
          refresh,
          counter
        } = this.props;
        return (
          <button onClick={() => refresh()}>
            Refresh
          </button>
        );
      }
    }
    

    操作/计数器.js:

    export function refresh() {
      // Do some local CRUD here.
      return {
        type: NO-OP
      };
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Tholle    7 年前

    您可以创建一个连续调用 setTimeout ,并在卸载组件时停止:

    例子

    class Counter extends Component {
      runRefresh = () => {
        this.timer = setTimeout(() => {
          this.props.refresh();
          this.runRefresh();
        }, 1000);
      };
    
      componentDidMount() {
        this.runRefresh();
      }
    
      componentWillUnmount() {
        clearTimeout(this.timer);
      }
    
      render() {
        const { refresh, counter } = this.props;
        return <button onClick={() => refresh()}>Refresh</button>;
      }
    }
    
        2
  •  1
  •   Hriday Modi Victor Manuel    7 年前

    我假设您需要在应用程序中定期刷新。

    所以在 redux 你可以写的动作创造者: 在这里 refreshInterval 在Action Creator中定义。

    startRefresh(){
      refreshIntervalId = window.setInterval(() => {
        refresh();
      }, 3000);
    }
    

    或者如果您只是从返回action对象 refresh 那么你应该使用 redux-thunk

    startRefresh => dispatch => (){
      refreshIntervalId = window.setInterval(() => {
        dispatch(refresh());
      }, 3000);
    }
    

    你可以叫这个 startRefresh componentDidMount 主应用程序组件的生命周期方法或来自您希望的组件的生命周期方法。

    componentDidMount(){
        this.props.startRefresh()
    }
    

    你也应该把 id 并清除此间隔 componentWillUnmount 生命周期方法。

    componentWillUnmount(){
        this.props.clearRefreshInterval()
    }
    

    clearRefreshInterval 只会是:

    clearRefreshInterval(){
        window.clearInterval(refreshIntervalId);
    }