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

React-Redux项目中类组件转函数组件的执行报错问题求助

解决方案:将Class组件重构为Function组件

重构后的完整代码

import React from "react";
import { useSelector } from "react-redux";
import Chart from "../containers/Chart";

const WeatherList = () => {
  // 从Redux store中获取weather状态
  const weather = useSelector(state => state.weather);

  // 定义渲染单条天气数据的函数
  const renderWeather = (results) => {
    // 先判断results是否存在list属性,避免报错
    if (!results?.list) return null;

    const temp = results.list.map(weather => (weather.main.temp - 273.15) * 9/5 + 32);
    const pressure = results.list.map(weather => weather.main.pressure);
    const humidity = results.list.map(weather => weather.main.humidity);

    return (
      <tr key={results.city.id}>
        <td>{results.city.name}</td>
        <td>
          <Chart color='yellow' data={temp} units='F'/>
        </td>
        <td>
          <Chart color='green' data={pressure} units='hPa'/>
        </td>
        <td>
          <Chart color='blue' data={humidity} units='%'/>
        </td>
      </tr>
    );
  };

  return (
    <table className="table table-hover">
      <thead>
        <tr>
          <th>City</th>
          <th>Temperature</th>
          <th>Pressure</th>
          <th>Humidity</th>
        </tr>
      </thead>
      <tbody>
        {/* 先判断weather是否为数组,再执行map */}
        {Array.isArray(weather) ? weather.map(renderWeather) : null}
      </tbody>
    </table>
  );
};

export default WeatherList;

关键修复点说明

  1. 状态获取方式替换:用useSelector直接从Redux store中提取weather状态,替代原有的connect和mapStateToProps,这是函数组件中获取Redux状态的更简洁方式。
  2. 消除this绑定问题:原Class组件中this.props.weather.map(this.renderWeather)会因为this指向丢失导致函数无法正确执行,重构为Function组件后,直接调用内部定义的renderWeather函数,不存在this绑定问题。
  3. 增加空值安全判断:
    • 在renderWeather中通过results?.list判断数据是否存在,避免因接口返回数据异常导致无法读取list的报错。
    • 在map前判断weather是否为数组,防止初始状态下weather为undefined或null时触发map函数报错。
  4. 函数定义简化:将原Class组件的类方法转为Function组件内部的普通函数,逻辑保持一致但写法更简洁。

常见问题排查

如果重构后仍无法读取list:

  • 检查Redux store中weather的结构是否正确,确保每个元素都包含list数组。
  • 确认接口返回的数据格式与原Class组件使用时一致,没有因接口更新导致数据结构变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:25:32