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

Laravel+React+InertiaJS开发搜索功能遇读取undefined属性错误

问题排查与解决方案

1. 「Cannot read properties of undefined (reading 'query')」错误排查

这个错误大概率不是query未定义,而是你访问query的方式有问题,常见原因:

  • 错误访问变量:模板中直接写value={query}而非value={data.query},或者在逻辑中直接引用query而不是从useForm返回的data对象中获取
  • useForm初始化缺省值:未给query设置初始默认值,导致组件渲染初期data.query为undefined。必须初始化带默认值的表单:
    const { data } = useForm({ query: '' }) // 给query设空字符串默认值
    
  • 组件未在Inertia上下文内:useForm是Inertia专属钩子,只能在被InertiaProvider包裹的组件/页面中使用。如果你的搜索组件是独立引入的,要确保它在项目默认的Inertia页面层级内

2. 「Cannot read properties of undefined (reading 'get')」错误解决

直接调用Inertia.get报错,是因为你没正确导入Inertia模块。React中必须从@inertiajs/react导入:

import { Inertia, useForm } from '@inertiajs/react'

不要依赖全局的Inertia对象,项目默认的Inertia配置不会暴露全局变量。

3. 输入框实时搜索实现(带防抖优化)

下面是完整的可运行代码,包含防抖处理避免频繁请求,同时正确使用Inertia和useForm:

import { useEffect } from 'react'
import { Inertia, useForm } from '@inertiajs/react'

export default function SearchPage() {
  // 初始化搜索表单,带默认值
  const { data, setData, get, processing } = useForm({
    query: ''
  })

  // 监听query变化,防抖后触发搜索请求
  useEffect(() => {
    const debounceTimer = setTimeout(() => {
      if (data.query.trim()) {
        // 方式1:用useForm的get方法,自动携带表单data作为参数
        get('/search', {
          preserveState: true,  // 保留页面状态(如滚动位置)
          preserveScroll: true
        })

        // 方式2:直接用Inertia.get,手动传递参数
        // Inertia.get('/search', { query: data.query }, {
        //   preserveState: true,
        //   preserveScroll: true
        // })
      }
    }, 300) // 300ms防抖,可根据需求调整

    return () => clearTimeout(debounceTimer)
  }, [data.query, get])

  // 输入框变更处理
  const handleInputChange = (e) => {
    setData('query', e.target.value)
  }

  return (
    <div className="search-container">
      <input
        type="text"
        value={data.query}
        onChange={handleInputChange}
        placeholder="输入关键词搜索..."
        disabled={processing} // 加载时禁用输入
      />
      {processing && <span>搜索中...</span>}
      {/* 这里渲染搜索结果,比如{results.map(...)} */}
    </div>
  )
}

额外说明:useForm方法与直接调用Inertia的区别

  • useForm的get/post会自动将表单data作为请求参数,无需手动拼接,还内置了processing状态用于加载提示
  • 直接调用Inertia方法需要手动传递参数,但灵活性更高,适合不需要表单状态管理的场景
  • 无论哪种方式,都建议添加preserveState和preserveScroll配置,避免搜索时页面状态重置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:05:41