You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在Action.js通过Axios发送多请求(下拉选队场景)

Solution: Dynamic URL Generation & Multiple Requests in getStats

Let's walk through how to solve both parts of your problem: dynamically creating the date-based URLs when the user selects a team, and handling multiple parallel API requests in your Redux action.

1. Dynamically Generate the URL Array

Instead of hardcoding the URLs, we'll build them using the league, team parameters passed from the dropdown selection, plus your fixed set of target dates. This ensures the URLs always match the selected team.

First, define your target dates as an array, then map over it to construct each full URL:

export function getStats(league, team, type) {
  return function(dispatch) {
    // Step 1: Define your target dates
    const targetDates = ['2019-08-30', '2019-09-30', '2019-10-30'];
    
    // Step 2: Dynamically build URLs using the incoming league/team params
    const URLs = targetDates.map(date => 
      `https://www.api-football.com/demo/api/v2/statistics/${league}/${team}/${date}`
    );

    // ... rest of your code
  }
}

This replaces your hardcoded URL array with one tailored to the user's selected team (the value from evt.target in selectHomeTeamStat). Your existing selectHomeTeamStat function doesn't need any changes—it already passes the correct leagueId and selected team ID to getStats.

2. Handle Multiple Parallel Requests

Use Promise.all to fetch all URLs at once, then process the combined results. Here's the complete getStats function with error handling and Redux dispatch logic:

import axios from 'axios';
// Assume you have these action type constants defined
import { STATS_REQUEST, STATS_SUCCESS, STATS_FAILURE } from './actionTypes';

export function getStats(league, team, type) {
  return function(dispatch) {
    // Dispatch a "request started" action to update loading state
    dispatch({ type: STATS_REQUEST });

    const targetDates = ['2019-08-30', '2019-09-30', '2019-10-30'];
    const URLs = targetDates.map(date => 
      `https://www.api-football.com/demo/api/v2/statistics/${league}/${team}/${date}`
    );

    // Helper function to fetch a single URL
    const fetchData = (URL) => {
      return axios.get(URL)
        .then(res => {
          // Attach the date to the response for easy mapping later
          return { date: URL.split('/').pop(), data: res.data };
        })
        .catch(err => {
          // Re-throw error to let Promise.all catch it with context
          throw new Error(`Failed to fetch stats for ${URL.split('/').pop()}: ${err.message}`);
        });
    };

    // Fetch all URLs in parallel
    const getAllData = () => Promise.all(URLs.map(fetchData));

    getAllData()
      .then(allStats => {
        // Dispatch success action with organized stats
        dispatch({
          type: STATS_SUCCESS,
          payload: {
            team,
            type,
            statsByDate: allStats.reduce((acc, item) => {
              acc[item.date] = item.data;
              return acc;
            }, {})
          }
        });
      })
      .catch(error => {
        // Dispatch failure action with error details
        dispatch({
          type: STATS_FAILURE,
          payload: error.message
        });
      });
  }
}

Key Details:

  • Loading State: We dispatch STATS_REQUEST first to let your reducer know data is being fetched (great for showing loading spinners in components).
  • Response Organization: In fetchData, we attach the date to each response so you can easily map results to their respective dates in the success payload.
  • Error Context: Failed requests include which date failed in the error message, making debugging easier.
  • Structured Payload: We reduce the array of stats into an object keyed by date, so your components/reducer can quickly access stats for a specific date.

3. Why This Works with Your Dropdown

Your existing selectHomeTeamStat function:

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

...already passes the selected team's ID (value) and league ID (leagueId) to getStats. The dynamic URL generation uses these values to build the correct URLs for the selected team—no extra changes needed here!

内容的提问来源于stack exchange,提问作者Koala7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:37:41