【问题标题】:React Axios create multiple request from one actionReact Axios 从一个操作创建多个请求
【发布时间】:2020-04-19 15:33:13
【问题描述】:

我有这种情况,用户在下拉列表中选择一个团队,这会向端点发送请求

  const selectHomeTeamStat = evt => {
    const { value } = evt.target;
    getStats(leagueId, value, 'home');
  }; 

假设请求被发送到 => https://www.api-football.com/demo/api/v2/statistics/524/40

我希望能够在我的 action.js 中创建多个请求,只需在 url 的末尾添加一个日期参数,类似于:

来自https://www.api-football.com/demo/api/v2/statistics/524/40的请求必须自动发送到这三个端点

  1. https://www.api-football.com/demo/api/v2/statistics/524/40/2019-08-30,
  2. https://www.api-football.com/demo/api/v2/statistics/524/40/2019-09-30
  3. https://www.api-football.com/demo/api/v2/statistics/524/40/2019-10-30

我的问题是如何在我的action.js 中发送这些多个请求?当他在我的下拉列表中选择一个团队时,我如何从用户操作中创建一个包含这 3 个 url 的数组?

这就是我的getStats 应该做的事情

export function getStats(league, team, type) {
  return function(dispatch) {

    let URLs= ["https://www.api-football.com/demo/api/v2/statistics/524/40/2019-08-30",
              "https://www.api-football.com/demo/api/v2/statistics/524/40/2019-09-30",
              "https://www.api-football.com/demo/api/v2/statistics/524/40/2019-10-30"]

    const getAllData = (URLs) => {
      return Promise.all(URLs.map(fetchData));
    }

    const fetchData = (URL) => {
      return axios
        .get(URL)
        .then(res => { ......

【问题讨论】:

  • 有什么问题?
  • 上一个已被删除的答案几乎是正确的
  • 看起来很简单。您需要实现生成三个日期字符串的规则。只有你知道如何做到这一点。我们没有。

标签: javascript reactjs promise get axios


【解决方案1】:
const url = "https://www.api-football.com/demo/api/v2/statistics";
let dates = ["2019-08-30", "2019-09-30", "2019-10-30"]

const getAllData = (dates, i) => {
  return Promise.all(dates.map(x => url + '/' + league + '/' + team + '/' + x).map(fetchData));
}

const fetchData = (URL) => {
  return axios
    .get(URL)
    .then(res => {

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2020-04-12
    • 2019-05-06
    • 2018-11-05
    • 2018-04-18
    相关资源
    最近更新 更多