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

React渲染OpenCage API结果列表时遇Element type invalid错误求助

问题原因与解决方案

这个错误的核心原因是你使用了未导入的Chakra UI组件,React无法识别这些未注册的组件类型,因此抛出"Element type is invalid"错误。

具体问题点

你的代码中使用了Box、Text、Input、Button、List、ListItem、Link这些Chakra UI组件,但只导入了NextLink和useState,完全缺失了这些组件的导入语句。单个结果展示时可能在父组件或其他上下文已经导入了部分组件,所以能正常运行,但列表渲染时因为用到更多未导入的组件(List、ListItem),直接触发了错误。

修正后的完整代码

import NextLink from "next/link";
import { useState } from "react";
// 导入所有用到的Chakra UI组件
import { Box, Text, Input, Button, List, ListItem, Link } from "@chakra-ui/react";

export default function Search() {
  const [searchTerm, setSearchTerm] = useState("");
  const [results, setResults] = useState([]);

  const handleSearch = async () => {
    if (!searchTerm.trim()) return;

    try {
      const response = await fetch(
        `https://api.opencagedata.com/geocode/v1/json?q=${searchTerm}&key=YOUR_API_KEY`
      );
      const data = await response.json();

      const cityResults = data.results.map((result) => ({
        id: `${result.geometry.lat},${result.geometry.lng}`,
        name: result.formatted,
        lat: result.geometry.lat,
        lng: result.geometry.lng,
      }));

      setResults(cityResults);
    } catch (error) {
      console.error("搜索出错:", error);
      alert("搜索失败,请重试");
    }
  };

  return (
    <Box p={4}>
      <Text mb={2}>Search for a city</Text>
      <Input 
        value={searchTerm} 
        onChange={(e) => setSearchTerm(e.target.value)}
        mb={2}
      />
      <Button onClick={handleSearch} mb={4}>Search</Button>
      <List>
        {results.map((city) => (
          <ListItem key={city.id} mb={2}>
            <NextLink href={`/city/${city.id}`} passHref>
              <Link color="teal.500" _hover={{ textDecoration: "underline" }}>
                {city.name}
              </Link>
            </NextLink>
          </ListItem>
        ))}
      </List>
      {results.length === 0 && searchTerm && <Text>No results found</Text>}
    </Box>
  );
}

额外优化建议

  • 添加try/catch捕获API请求异常,避免请求失败导致页面崩溃
  • 给组件添加间距(比如mb属性),提升UI美观度
  • 当搜索后无结果时,显示提示文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:14:58