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

React类组件转函数组件出现useState调用规则和变量未定义错误求助

正确实现代码
import React, { useState, useEffect } from 'react';
import AssetTypeService from './AssetTypeService'

// 组件名首字母必须大写,符合React组件命名规则
const GetAssetTypeNameFunction = (props) => {
  // 定义state存储接口返回的资产类型名称与加载状态
  const [assettypeName, setAssettypeName] = useState('')
  const [isLoading, setIsLoading] = useState(true)

  // 用useEffect模拟componentDidMount生命周期,仅在组件挂载/查询参数变化时执行接口调用
  useEffect(() => {
    // 接收父组件传入的查询参数datafromparent发起请求
    AssetTypeService.getAssetTypeById(props.datafromparent).then((res) => {
      const assettype = res.data
      setIsLoading(false)
      // 将返回的名称存入state触发视图更新
      setAssettypeName(assettype.assettypeName)
    })
  }, [props.datafromparent]) // 依赖项配置:父组件传入的查询参数变化时自动重新查询

  return (
    <div>
      {isLoading ? '' : assettypeName}
    </div>
  )
}

export default GetAssetTypeNameFunction
报错问题说明
  • 第一个hooks规则报错:React要求所有函数组件命名必须以大写字母开头,原代码组件名为小写开头的getAssetTypeNameFunction,被eslint判定为普通函数而非React组件,因此不允许调用hooks
  • 第二个assettype未定义报错:你在then回调内部用let定义了assettype变量,该变量仅在回调函数的块级作用域内有效,return的模板部分无法访问该变量;同时接口请求是异步操作,你没有将返回结果存入state,视图无法拿到异步返回的数据
  • 额外逻辑问题:原代码没有接收父组件传入的参数,接口查询参数写死了固定值;没有用useEffect包裹接口调用逻辑,会导致组件每次渲染都重复发起接口请求;没有做初始值兼容,接口返回前访问字段会抛出运行时错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:33:00