【问题标题】:ReactJS SetTimeout / setInterval [duplicate]ReactJS SetTimeout / setInterval [重复]
【发布时间】:2021-10-02 03:44:49
【问题描述】:

我正在尝试让以下内容每 30 秒重新加载一次。

componentDidMount() {
  fetch('https://example.com/json')
    .then((res) => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          items: result.data,
        });
      },
      // Note: it's important to handle errors here
      // instead of a catch() block so that we don't swallow
      // exceptions from actual bugs in components.
      (error) => {
        this.setState({
          isLoaded: true,
          error,
        });
      },
    );
}

我尝试将其包装在 setInterval 中,但没有成功。我想知道如何将它变成一个函数,以便我可以根据需要重新加载它。

【问题讨论】:

标签: reactjs next.js settimeout setinterval


【解决方案1】:

假设您想在进入组件后每 30 秒获取一次数据,然后在组件退出时停止此获取:

               componentDidMount() {
                this.myInterval = setInterval(() => {
                  fetch('https://example.com/json')
                    .then(res => res.json())
                    .then(
                    (result) => {
                        this.setState({
                        isLoaded: true,
                        items: result.data
                        });
                        
                    },
                    // Note: it's important to handle errors here
                    // instead of a catch() block so that we don't swallow
                    // exceptions from actual bugs in components.
                    (error) => {
                        this.setState({
                        isLoaded: true,
                        error
                        });
                    });
                 }, 30000);
               }

               componentWillUnmount() {    
                   clearInterval(this.myInterval);
               }

应该够了。

【讨论】:

    【解决方案2】:

    我建议您将 fetch 函数从 componentDidMount 方法中取出。把它写在一个调用函数的 loadData() 或者任何你想命名的地方。然后在 loadData() 函数中用 like 包装你的获取逻辑 关注。

    const loadData = () => { 
    setInterval(
    async function(){
      //your fetch logic here with await
    }, 30000);
    }
    
    componentDidMount() {
    loadData()
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 2017-03-31
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      相关资源
      最近更新 更多