【问题标题】:can api be called repetitively from react js可以从react js重复调用api吗
【发布时间】:2020-05-08 12:13:23
【问题描述】:

我是新来的反应。有人可以帮助我了解如何每 15 分钟重复一次 api 调用并将数据呈现到应用程序上吗?请在下面找到代码。我认为使用 setInterval/setTimeout 可能是一种选择。但是,哪一个是最好的,请帮我解决下面的代码。提前致谢!

import React from 'react';
import axios from 'axios';

export default class UserList extends React.Component {
    state = {
        users: []
    };

    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const users = res.data;
                this.setState({users});
            })
    }

    render() {
        return (
            <ul>
                {this.state.users.map(user => <li>{user.name}</li>)}
            </ul>
        )
    }
}

【问题讨论】:

  • 您可以使用其中任何一种,它应该可以工作,但只是好奇,为什么您想每 15 分钟发出一次请求。您的要求是否要求显示实时数据?如果是,那么我想您可以使用setInterval,或者只需引入一个刷新按钮并在需要时拨打电话。
  • 两者都有效,但由于您试图每隔一段时间运行一些东西,我会说使用setInterval。这就是它的目的。

标签: javascript reactjs axios react-hooks


【解决方案1】:

您可以使用其中任何一种,它应该可以工作,但只是好奇,为什么您想每 15 分钟发出一次请求。您的要求是否要求显示实时数据?如果是,那么我想您可以使用setInterval,如下所示,或者只需引入一个刷新按钮并在需要时拨打电话

import React, { Component } from 'react';
import axios from 'axios';

const INTERVAL_DURATION = 15 * 1000 * 60;

export default class UserList extends Component {
  state = {
    users: [],
  };

  componentDidMount() {
    this._fetchUserInterval = setInterval(this._fetchUsers, INTERVAL_DURATION);
  }

  componentWillUmount() {
    clearInterval(this._fetchUserInterval);
  }

  _fetchUsers = () => {
    axios.get(`https://jsonplaceholder.typicode.com/users`).then(res => {
      this.setState({ users: res.data });
    });
  };

  render() {
    const { users } = this.state;

    return (
      <ul>
        {users.map((user, index) => (
          <li key={index}>{user.name}</li>
        ))}
      </ul>
    );
  }
}

【讨论】:

    【解决方案2】:

    尝试使用setInterval()函数-

    componentDidMount() {
      setInterval(() => {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
         .then(res => {
            const users = res.data;
            this.setState({users});
          });
      }, (15 * 1000 * 60));
    }
    

    【讨论】:

      【解决方案3】:

      试试这个。使用setInterval 并存储intervalId,以便在组件卸载时进行清理。

      import React from 'react';
      import axios from 'axios';
      
      export default class UserList extends React.Component {
          state = {
              users: [],
          };
      
          componentDidMount() {
              // Keep the interval id
              this.intervalId = setInterval(this.getData, 900000);
          }
      
          componentWillUnmount() {
              // use intervalId to clear the interval onUnmount
              clearInterval(this.intervalId);
          }
      
          getData() {
              axios.get(`https://jsonplaceholder.typicode.com/users`)
                  .then(res => {
                      const users = res.data;
                      this.setState({ users });
                  })
                  .catch(error => console.log(error))
          }
      
          render() {
              return (
                  <ul>
                      {this.state.users.map(user => <li>{user.name}</li>)}
                  </ul>
              )
          }
      }
      

      【讨论】:

        【解决方案4】:

        setTimeout() 只触发一次,而对于重复性任务setInterval() 是选项。

        你可以走这条路

        componentDidMount() {
          setInterval(() => {
            axios.get(`https://jsonplaceholder.typicode.com/users.then(res => {
                const users = res.data;
                this.setState({users});
              });
          }, (15 * 1000 * 60));
        }
        

        另外,由于它是一个类组件,您必须清除componentWillUnmount()getDerivedStateFromProps() 中的所有订阅。

        额外说明:在 JSX 中迭代时始终使用 keys

        render() {
                return (
                    <ul>
                        {this.state.users.map((user, index) 
                            => <li key={index}>{user.name}</li>)}
                    </ul>
                )
            }
        

        【讨论】:

          【解决方案5】:

          两者都应该工作,但使用 setInterval 将是一个更简单的选择。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-14
            • 1970-01-01
            • 2017-08-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-19
            • 1970-01-01
            相关资源
            最近更新 更多