React组件新增函数时报Cannot read properties of undefined (reading 'map')错误
问题原因与解决方案
你遇到的编译阶段Syntax error核心原因是新增的test函数位置错误:类组件的实例方法必须定义在类的直接作用域下,不能嵌套在render方法、其他类方法的内部。如果你把test(){}写在了render函数的花括号内部,会导致TypeScript/Babel编译逻辑异常,误解析代码结构触发该map类编译报错。
正确的写法是把test函数和PopulateData、get方法平级,放在类的根层级:
export class FetchData extends Component<IProps, IState>{ static DisplayName = FetchData.Name; constructor(props: IProps) { super(props); this.state = { TreeRoot: null, Controllers: null, Loading: true, LoginToken: null }; } // 正确位置:和其他类方法平级 test(){ return true; } componentDidMount() { this.PopulateData(); } // 其他原有代码... }
现有代码潜在问题修复
以下问题如果不修复,后续运行时也会触发同类属性读取报错:
- 类方法this丢失问题
你当前定义的PopulateData、get等普通实例方法,调用时会丢失this指向,导致访问this.state/this.props时报undefined。建议改成箭头函数写法,自动绑定this:
- 类方法this丢失问题
PopulateData = async () => { // 原有逻辑保持不变 } get = async (url: string): Promise<any> => { // 原有逻辑保持不变 }
- 类型与初始值不匹配问题
IState中Controllers定义为[]类型,初始值却赋值为null,且空数组默认类型为never[]无法存储后续接口返回的数据,建议修改定义和初始值:
- 类型与初始值不匹配问题
// 修改IState定义 interface IState { TreeRoot?: TreeNodeInfo; Controllers: any[]; // 有明确Controller类型可替换any Loading: boolean; LoginToken?: string; } // 修改constructor中的state初始值 this.state = { TreeRoot: null, Controllers: [], Loading: true, LoginToken: null };
- 渲染前非空判断补充
虽然你做了Loading状态判断,仍建议在调用renderTree前补充TreeData的非空校验,避免接口异常返回空Root时运行报错:
- 渲染前非空判断补充
return ( <TreeView aria-label="rich object" defaultCollapseIcon={<ExpandMoreIcon />} defaultExpanded={['root']} defaultExpandIcon={<ChevronRightIcon />} sx={{ height: 840, flexGrow: 1, maxWidth: 400, overflowY: 'auto' }} > {TreeData ? renderTree(TreeData) : null} </TreeView> );
- renderTreeNewLevel函数问题
当前该函数是async异步函数,且没有return返回值,不能直接在JSX中渲染使用。如果后续需要加载二级节点,建议通过state存储异步获取的节点数据,再触发渲染。
- renderTreeNewLevel函数问题
内容的提问来源于stack exchange,提问作者mor
相关产品推荐
相关产品推荐

