如何将此刷新动作称为连续后台作业

时间:2018-06-26 16:05:48

标签: javascript reactjs redux react-redux

这是电子应用程序的一部分,在按下UI上的刷新按钮时会调用此操作。我想使其自动刷新。我该怎么办?

Components / counter.js:

await getSearchTerms(contentFiles[i])
searchIndex.push(object))

actions / counter.js:

export default class Counter extends Component<Props> {
  props: Props;

  render() {
    const {
      refresh,
      counter
    } = this.props;
    return (
      <button onClick={() => refresh()}>
        Refresh
      </button>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

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

因此,在redux动作创建者中,您可以编写: 这里refreshInterval是在动作创建者中定义的。

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

或者,如果您只是从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);
}

答案 1 :(得分:1)

您可以创建一个连续调用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>;
  }
}