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

《React Hooks in Action》练习报错:static.json中filter方法未找到

问题排查与解决
  • 检查导入方式是否正确
    如果你的static.json是包含bookables字段的对象(和作者仓库结构一致),正确导入逻辑应该是:

    // 默认导入整个JSON对象
    import staticData from './static.json';
    // 取出bookables数组
    const bookables = staticData.bookables;
    // 此时调用filter方法即可正常执行
    const filteredItems = bookables.filter(...);
    

    你之前可能误用了命名导入import { bookables } from './static.json',但React项目中JSON文件默认是以单个对象作为默认导出,并非拆分的命名导出字段。这种错误写法会导致你拿到undefined,或者在部分打包逻辑下,误将数组索引识别为导出项,出现0、1、2这类奇怪的导出提示。

  • 确认static.json的结构
    确保文件结构和作者仓库完全一致,顶级是包含bookables数组的对象,而非直接将数组作为JSON根节点。正确结构示例:

    {
      "bookables": [
        {
          "id": 1,
          "title": "Meeting Room",
          "type": "room"
        },
        // 其他条目...
      ]
    }
    
  • 避免错误的导入写法
    不要使用import * as bookables from './static.json',这种写法会把JSON内容转换为以索引(若JSON是数组)或顶级属性为键的对象,此时bookables并非数组,自然不存在filter方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 20:33:12