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

如何在Redux中带参数调用天气API?Axios多参数URL获取方案

在Redux中结合Axios通过多URL参数获取天气数据的实现方案

没问题!我来帮你梳理在Redux中结合Axios,通过URL里的城市和国家参数获取天气数据的完整方案。首先得注意你代码里的小拼写问题(weathe要改成weather),然后因为Axios是异步请求,Redux本身只支持同步action,所以我们需要用到redux-thunk中间件来处理异步逻辑。下面是一步步的实现:

1. 安装必要依赖

首先确保你已经安装了Axios和Redux Thunk:

npm install axios redux-thunk
# 或者用yarn
yarn add axios redux-thunk

2. 完善Action逻辑(处理异步请求)

我们需要定义三种action类型来管理请求的不同状态(发起、成功、失败),然后编写getWeather异步action:

先定义Action Types

创建actionTypes.js:

export const FETCH_WEATHER_START = 'FETCH_WEATHER_START';
export const FETCH_WEATHER_SUCCESS = 'FETCH_WEATHER_SUCCESS';
export const FETCH_WEATHER_FAILURE = 'FETCH_WEATHER_FAILURE';

编写异步Action函数

修改你的weatherActions.js:

import axios from 'axios';
import { FETCH_WEATHER_START, FETCH_WEATHER_SUCCESS, FETCH_WEATHER_FAILURE } from './actionTypes';

const API_KEY = "a3de5cffde10c377d199699b3da6fc6f";

export const getWeather = (city, country) => {
  // Redux Thunk允许我们返回一个函数,而不是普通action对象
  return (dispatch) => {
    // 分发"请求开始"的action,用来显示加载状态
    dispatch({ type: FETCH_WEATHER_START });

    // 拼接正确的请求URL,注意修复拼写错误
    const URL = `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`;

    // 发起Axios GET请求
    axios.get(URL)
      .then(response => {
        // 请求成功,分发携带天气数据的action
        dispatch({
          type: FETCH_WEATHER_SUCCESS,
          payload: response.data
        });
      })
      .catch(error => {
        // 请求失败,分发错误信息的action
        dispatch({
          type: FETCH_WEATHER_FAILURE,
          payload: error.message || '获取天气数据失败,请稍后重试'
        });
      });
  };
};

3. 配置Redux Store(应用Thunk中间件)

要让Redux支持异步action,必须在创建store时应用Thunk中间件:

import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import weatherReducer from './reducers/weatherReducer';

// 合并reducers(如果有多个的话)
const rootReducer = combineReducers({
  weather: weatherReducer
});

// 创建store并应用Thunk中间件
const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;

4. 编写Reducer处理Action

创建weatherReducer.js来管理天气相关的状态:

import { FETCH_WEATHER_START, FETCH_WEATHER_SUCCESS, FETCH_WEATHER_FAILURE } from '../actions/actionTypes';

// 初始状态
const initialState = {
  weatherData: null,
  isLoading: false,
  errorMessage: null
};

const weatherReducer = (state = initialState, action) => {
  switch(action.type) {
    case FETCH_WEATHER_START:
      return {
        ...state,
        isLoading: true,
        errorMessage: null
      };
    case FETCH_WEATHER_SUCCESS:
      return {
        ...state,
        isLoading: false,
        weatherData: action.payload
      };
    case FETCH_WEATHER_FAILURE:
      return {
        ...state,
        isLoading: false,
        errorMessage: action.payload
      };
    default:
      return state;
  }
};

export default weatherReducer;

5. 在组件中调用Action并展示数据

最后,在React组件中通过connect把Redux的state和action连接起来,调用getWeather时传入城市和国家参数:

import React, { useState } from 'react';
import { connect } from 'react-redux';
import { getWeather } from './actions/weatherActions';

const WeatherApp = ({ getWeather, weather }) => {
  const [city, setCity] = useState('');
  const [country, setCountry] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    // 调用action,传入用户输入的城市和国家
    getWeather(city, country);
  };

  return (
    <div style={{ padding: '20px' }}>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="输入城市(如Beijing)"
          value={city}
          onChange={(e) => setCity(e.target.value)}
          style={{ marginRight: '10px' }}
        />
        <input
          type="text"
          placeholder="输入国家代码(如CN)"
          value={country}
          onChange={(e) => setCountry(e.target.value)}
          style={{ marginRight: '10px' }}
        />
        <button type="submit">获取天气</button>
      </form>

      {/* 展示加载状态 */}
      {weather.isLoading && <p>正在获取天气数据...</p>}

      {/* 展示错误信息 */}
      {weather.errorMessage && <p style={{ color: 'red' }}>{weather.errorMessage}</p>}

      {/* 展示天气数据 */}
      {weather.weatherData && (
        <div style={{ marginTop: '20px' }}>
          <h2>{weather.weatherData.name}, {weather.weatherData.sys.country}</h2>
          <p>当前温度: {weather.weatherData.main.temp}°C</p>
          <p>天气状况: {weather.weatherData.weather[0].description}</p>
          <p>湿度: {weather.weatherData.main.humidity}%</p>
        </div>
      )}
    </div>
  );
};

// 把Redux中的天气状态映射到组件props
const mapStateToProps = (state) => ({
  weather: state.weather
});

// 把action映射到组件props
const mapDispatchToProps = {
  getWeather
};

export default connect(mapStateToProps, mapDispatchToProps)(WeatherApp);

几个关键注意点

  • URL拼写检查:你之前的代码里把weather写成了weathe,这会导致请求失败,一定要修正
  • 异步Action依赖:Redux本身不支持异步逻辑,必须借助redux-thunk中间件才能让action返回函数
  • 状态管理:通过分发起始、成功、失败的action,能更好地控制加载状态和错误提示,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:05:46