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

React类组件转函数组件渲染时出现props undefined报错如何解决?

错误原因

函数组件不存在this实例,你沿用类组件的this.props写法触发了undefined读取错误,同时propTypes的定义方式不符合函数组件规范。

具体修正点

  • 函数组件的props通过函数入参传递,直接接收后即可调用,无需通过this访问
  • propTypes需要挂载为组件的静态属性,不能在组件内部定义为函数
  • 移除不必要的命名导出export const Devices,避免调用未经过redux connect的组件

修正后完整代码

import React, { Fragment, useEffect } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getDevices } from '../../actions/deviceActions';

// 入参接收props,也可以直接解构为{ deviceState, getDevices }简化后续调用
const Devices = (props) => {
  useEffect(() => {
    props.getDevices();
  }, []);

  return (
    <Fragment>
      <h2>设备列表</h2>
      <div>
        {props.deviceState.map(device => (
          <h1 key={device.id}>{device.make}</h1>
        ))}
      </div>
    </Fragment>
  );
}

// 正确的propTypes定义方式
Devices.propTypes = {
  deviceState: PropTypes.array.isRequired,
  getDevices: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  deviceState: state.device.device
});

export default connect(mapStateToProps, { getDevices })(Devices);

可选优化

你可以直接解构props参数简化代码,组件头部修改为如下写法即可,后续代码中可以直接调用getDevices()和deviceState,无需加props.前缀:

const Devices = ({ deviceState, getDevices }) => {

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:36:04