返回

React+Redux天气预报项目实战:入门指南

前端

React+Redux天气预报项目实战

在前端开发领域,React和Redux是两大重量级框架,它们提供了强大而灵活的工具,可以帮助您构建出色的用户界面和应用程序。本教程将带您一步一步地使用React和Redux创建一个实用的天气预报项目,涵盖前端开发的各个阶段。无论您是React新手还是经验丰富的开发者,都能从中受益,并对React和Redux的强大功能有更深刻的理解。

项目概述

天气预报项目将允许用户输入城市名称,然后显示该城市当前的天气信息,包括天气状况、温度、风速、湿度等。用户还可以查看未来几天的天气预报。

项目结构

项目将使用以下技术栈:

  • React
  • Redux
  • Axios
  • Sass

项目结构如下:

├── src
│   ├── actions
│   ├── components
│   ├── containers
│   ├── reducers
│   ├── styles
│   └── index.js
├── package.json
└── README.md

步骤1:设置项目

首先,使用create-react-app工具创建一个新的React项目:

npx create-react-app react-weather-app

步骤2:安装依赖项

接下来,安装必要的依赖项:

npm install --save redux react-redux axios sass

步骤3:创建Redux store

在src目录下创建一个store.js文件,用以创建Redux store:

import { createStore } from 'redux';

const initialState = {};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'SET_WEATHER':
      return {
        ...state,
        weather: action.payload,
      };
    default:
      return state;
  }
};

const store = createStore(rootReducer);

export default store;

步骤4:创建React组件

在src/components目录下创建WeatherApp.js文件,用以定义React组件:

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { setWeather } from '../actions';
import axios from 'axios';

const WeatherApp = () => {
  const [city, setCity] = useState('');
  const dispatch = useDispatch();

  const fetchWeather = () => {
    axios
      .get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.REACT_APP_OPENWEATHERMAP_API_KEY}`)
      .then((res) => {
        dispatch(setWeather(res.data));
      })
      .catch((err) => {
        console.error(err);
      });
  };

  return (
    <div>
      <h1>Weather App</h1>
      <input type="text" value={city} onChange={(e) => setCity(e.target.value)} />
      <button onClick={fetchWeather}>Get Weather</button>
      {weather && (
        <div>
          <h2>{weather.name}</h2>
          <p>{weather.weather[0].description}</p>
          <p>Temperature: {weather.main.temp} °C</p>
          <p>Wind Speed: {weather.wind.speed} m/s</p>
          <p>Humidity: {weather.main.humidity}%</p>
        </div>
      )}
    </div>
  );
};

export default WeatherApp;

步骤5:运行项目

最后,运行项目:

npm start

总结

通过本教程,您已经成功地使用React和Redux构建了一个实用的天气预报项目。您不仅学会了如何使用React和Redux开发前端应用程序,还对天气预报API的使用有了一定了解。希望本教程对您有所帮助,如果您有任何疑问,欢迎在评论区留言。