首个React JS应用报错求助:附代码及错误截图
React应用错误修复与地图功能实现方案
一、当前错误修复
你的应用核心错误源于React组件规范未遵守及部分逻辑的潜在问题,具体修复点如下:
组件名首字母大写
React要求自定义组件必须以大写字母开头,否则会被识别为原生HTML标签。将代码中的<homeLink />改为<HomeLink />。静态资源路径修正
在Next.js中,静态资源需放在项目根目录的public文件夹下,将countries.xlsx移至该目录后,修改fetch路径:
const response = await fetch('/countries.xlsx');
- 避免undefined报错
handleChange中如果未找到对应国家,find会返回undefined,直接调用Object.entries会触发错误,优化逻辑:
const handleChange = (e) => { const selected = e.target.value; setSelectedCountry(selected); const matchedCountry = countries.find(country => country.Country === selected); setCountryData(matchedCountry || {}); // 未找到则设为空对象 };
- 表格表头渲染修正
Object.entries(countryData)返回的是[键名, 键值]格式的数组,之前的表头渲染逻辑错误,改为:
<thead> {Object.entries(countryData).map(([key]) => ( <th key={key}>{key}</th> ))} </thead>
二、完整修复后代码
import * as XLSX from 'xlsx'; import React, { useState, useEffect } from 'react'; import Link from 'next/link'; export const HomeLink = () => { return ( <div> <h1>Home Page</h1> <p>Welcome to my app!</p> <p>Click <Link href="/dashboard">here</Link> to go to the dashboard.</p> </div> ) } export default function CountryData() { const [countries, setCountries] = useState([]); const [selectedCountry, setSelectedCountry] = useState(''); const [countryData, setCountryData] = useState({}); const handleChange = (e) => { const selected = e.target.value; setSelectedCountry(selected); const matchedCountry = countries.find(country => country.Country === selected); setCountryData(matchedCountry || {}); }; useEffect(() => { const readExcel = async () => { const response = await fetch('/countries.xlsx'); const data = await response.arrayBuffer(); const workbook = XLSX.read(data, { type: 'array' }); const sheet = workbook.Sheets['World']; const countryList = XLSX.utils.sheet_to_json(sheet); setCountries(countryList); }; readExcel(); }, []); return ( <div> <HomeLink /> <select onChange={handleChange}> <option value="">--Select Country--</option> {countries.map((country, index) => ( <option key={index} value={country.Country}> {country.Country} </option> ))} </select> {selectedCountry && ( <div> <h2>{selectedCountry}</h2> <table> <thead> {Object.entries(countryData).map(([key]) => ( <th key={key}>{key}</th> ))} </thead> <tbody> <tr> {Object.values(countryData).map((value, index) => ( <td key={index}>{value}</td> ))} </tr> </tbody> </table> </div> )} </div> ); }
三、地图功能实现方案(点击国家展示数据)
推荐使用react-simple-maps实现轻量交互地图,步骤如下:
1. 安装依赖
npm install react-simple-maps
2. 集成地图组件
在CountryData组件中添加地图模块,核心是给每个国家路径绑定点击事件,匹配Excel中的国家名称:
import { ComposableMap, Geographies, Geography } from 'react-simple-maps'; // 地图国家名称与Excel名称映射(根据你的实际数据调整) const countryNameMap = { "United States of America": "USA", "China": "China", // 补充其他国家的映射关系 }; // 在组件return中添加地图区域 {countries.length > 0 && ( <div style={{ width: '800px', height: '500px', margin: '20px auto' }}> <ComposableMap projection="geoMercator"> <Geographies geography="/world-110m.json"> {({ geographies }) => geographies.map(geo => { // 转换地图国家名称为Excel中的对应名称 const mapCountryName = geo.properties.name; const excelCountryName = countryNameMap[mapCountryName] || mapCountryName; // 检查Excel中是否存在该国家 const hasCountry = countries.some(c => c.Country === excelCountryName); return ( <Geography key={geo.rsmKey} geography={geo} fill={hasCountry ? "#69b3a2" : "#dedede"} stroke="#ffffff" onClick={() => { if (hasCountry) { setSelectedCountry(excelCountryName); const matched = countries.find(c => c.Country === excelCountryName); setCountryData(matched || {}); } }} style={{ hover: { fill: "#f53" }, pressed: { fill: "#e42" } }} /> ); }) } </Geographies> </ComposableMap> </div> )}
3. 注意事项
world-110m.json是地图数据文件,可从react-simple-maps官方示例获取,放入public目录。- 必须根据你的Excel数据调整
countryNameMap,确保地图返回的国家名称能匹配到Excel的Country列值。 - 可根据需求自定义地图的样式、大小和交互效果。
内容的提问来源于stack exchange,提问作者TheTriankh
相关产品推荐
相关产品推荐

