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

React使用CoreUI模板触发handleSubmit时报Cannot read properties of undefined (reading 'form')错误

你的代码使用的是React函数组件,函数组件不存在类组件的this实例对象,你两处使用this的逻辑都会触发报错:

  1. 表单ref绑定中使用this.form存储引用
  2. handleSubmit中使用this.state读取表单值

修复步骤


1. 导入需要的Hook

在文件头部导入useRef,补充缺少的表单状态定义:

import { useState, useEffect, useRef } from 'react'

组件内部新增表单状态和表单ref:

const DataSources = () => {
  const [collapsed, setCollapsed] = useState(true)
  const [showElements, setShowElements] = useState(true)
  const [tableEntries, setTableEntries] = useState([])
  // 新增表单状态
  const [formValue, setFormValue] = useState('')
  const [accessToken, setAccessToken] = useState('')
  // 新增表单ref,替代this.form
  const formRef = useRef(null)
  // 其余原有代码...
}

2. 重写handleSubmit提交函数

补充阻止表单默认提交的逻辑,直接使用定义的state变量读取表单值:

function handleSubmit(e){
    // 阻止表单默认刷新页面行为
    e.preventDefault()
    const article = { 
      "connectionType":"InstagramConnection",
      "id":"e5ee8320-a307-448b-a0ed-0829a187050f",
      "name":formValue,
      "accessCredentials":{"id":2,"token":accessToken} 
    };
    const headers = {
      "Content-Type": "application/json; charset=utf-8"
    };
    Axios.post('http://localhost:8080/api/connections', article, { headers })
        .then(response => console.log(response.data.id))
        .catch(err => console.log(err));
};

3. 修改表单ref绑定和提交按钮触发逻辑

把CForm的ref属性替换为用useRef创建的对象:

<CForm 
  ref={formRef} 
  className="form-horizontal" 
  onSubmit={handleSubmit}
>

修改提交按钮的点击触发逻辑:

<CButton 
  type="submit" 
  size="sm" 
  color="primary" 
  value="Submit" 
  onClick={ () => { formRef.current.dispatchEvent(new Event('submit')) } }
>
  <CIcon name="cil-scrubber" /> Add Connection
</CButton>

4. 补充表单输入控件绑定(必须)

你当前表单内只有Facebook组件,需要补充对应的输入控件绑定state才能拿到表单值:

<CFormGroup>
  <CInput 
    label="应用名称" 
    value={formValue} 
    onChange={(e) => setFormValue(e.target.value)} 
    placeholder="请输入应用名称"
  />
  <CInput 
    label="Access Token" 
    value={accessToken} 
    onChange={(e) => setAccessToken(e.target.value)} 
    placeholder="请输入授权凭证"
  />
  <Facebook />
</CFormGroup>

5. 优化列表查询逻辑(可选)

原useEffect中循环调用setTableEntries可以简化为单次更新,减少不必要的重渲染:

useEffect(() => {
  Axios.get('http://localhost:8080/api/connections')
   .then(res => {
      console.log(res.data);
      setTableEntries(res.data);
   })
   .catch(err => console.log(err));
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:15:02