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

React Img-Mapper库刷新时无法正确加载JSON数据,抛出TypeError: Cannot read properties of undefined (reading 'length')错误

React Img-Mapper库刷新时无法正确加载JSON数据,抛出TypeError: Cannot read properties of undefined (reading 'length')错误

我之前一直在用react-img-mapper库,原本一切正常,但当我需要添加条件渲染另一个组件的功能时,问题出现了:只要我切换组件的显示状态(控制showBook的true/false),页面刷新后库就会抛出错误,提示无法读取undefined的length属性。后来我还发现,不管是哪种方式重新加载带img-map的页面(比如通过路由跳转回当前页面),都会触发同样的错误——哪怕初始加载时坐标数据明明是正常的,我也通过console.log确认过数据已经正确填充了。

相关代码

我的页面组件代码如下:

"use client"
import { React, useEffect, useState } from "react";
import ImageMapper from "react-img-mapper";
import { useRouter } from 'next/navigation'
import coords from "/public/JSON/coords.js";
import RecipeBook from "./RecipeBook";

export default function Kitchen() {
  const router = useRouter();
  const [showBook, setShowBook] = useState(true);
  const [kitchenCoords, setKitchenCoords] = useState(null);

  useEffect(() => {
      setKitchenCoords(coords.kitchenCoords);
  }, []); 
    
  if (!kitchenCoords) {
    return (<body className="kitchen"><h1>Loading...</h1></body>)
  }
  
  return (
    <body className="kitchen">
      <div className="tvbgContainer">
        <ImageMapper className="tvbg"
          map={{
              name:"my-map", 
              areas: kitchenCoords
              }}
          src={'/background/kitchenpage.png'}
          active={true}
          responsive={true}
          parentWidth={900}
          length={900}
          width={900}
          onClick={(e) => {
            // if it's one of the buttons, redirect there
            (e.title == "/about/me/" || e.title == "/about/credits/" || e.title == "/") ? router.push(e.title) 
            : // else show book
            // setShowBook(!showBook);
            console.log(kitchenCoords);
          }}
          />
      </div>
      {showBook && 
        <RecipeBook setShowBook={setShowBook}/>
      }
    </body>
  );
}

坐标JSON文件(简化后):

let kitchenCoords = [
  {
    "id": "homeButton",
    "title": "/",
    "shape": "rect",
    "fillColor": "rgba(0,0,0,0)",
    "strokeColor": "rgba(0,0,0,0)",
    "lineWidth": 2.5,
    "coords": [530,738,586,791]
  },
...
]
export default {homeCoords, kitchenCoords};

抛出的错误信息

TypeError: Cannot read properties of undefined (reading 'length')

NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

解决方案

后来我更新到了react-img-mapper的alpha版本,这个问题就直接解决了!

另外我也考虑过换一种加载JSON数据的方式会不会有帮助,不过目前更新版本已经完美解决了我的问题,如果你也遇到类似情况可以试试这个方法。

备注:内容来源于stack exchange,提问作者user

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:13:00