React项目变量未定义报错求助:contactList等变量未定义
React变量未定义问题解决
问题场景
正在学习React,开发通讯录项目时遇到变量未定义的ESLint报错,以下是相关代码和错误信息:
App.js代码
import React, { useState, useEffect } from "react"; import { v4 as uuid } from "uuid"; import "./App.css"; import Header from "./Header"; import AddContact from "./AddContact"; import ContactList from "./ContactList"; function App() { const LOCAL_STORAGE_KEY = "contacts"; const [contacts, setContacts] = useState( JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) ?? [] ); const addContactHandler = (contact) => { console.log(contact); setContacts([...contacts, { id: uuid(), ...contact }]); }; const removeContactHandler = (id) => { const newContactList = contacts.filter((contact) => { return contact.id !== id; }); setContacts(newContactList); }; useEffect(() => { localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts)); }, [contacts]); return ( <div className="ui container"> <Header /> <AddContact addContactHandler={addContactHandler} /> <ContactList contacts={contacts} getContactId={removeContactHandler} /> </div> ); } export default App;
ContactList.js代码
import React from "react"; import ContactCard from "./ContactCard"; const ContactList = (props) => { console.log(props); const deleteContactHandler = (id) => { props.getContactId(id); }; const renderContactList = props.contacts.map((contact) => { return ( <ContactCard contact={contact} clickHandler={deleteContactHandler} key={contact.id} /> ); }); return <div className="ui celled list">{ContactList}</div>; }; export default ContactList;
报错信息(翻译后)
[eslint]
src\components\conatctList.js
第8行16列:'contactList' 未定义 no-undefsrc\components\contactList.js
第16行38列:'rendercontactList' 未定义 no-undef
第19行16列:'contactList' 未定义 no-undef
问题原因及解决方案
核心错误
- 变量引用错误:在
ContactList组件的return语句中,错误使用了组件自身名称ContactList,而非之前定义的渲染列表变量renderContactList。 - 大小写拼写问题:报错中的
rendercontactList是全小写,而代码里定义的是驼峰式renderContactList,属于大小写不一致导致的误解,但核心问题还是return里的变量引用错误。
修改后的ContactList.js代码
import React from "react"; import ContactCard from "./ContactCard"; const ContactList = (props) => { console.log(props); const deleteContactHandler = (id) => { props.getContactId(id); }; const renderContactList = props.contacts.map((contact) => { return ( <ContactCard contact={contact} clickHandler={deleteContactHandler} key={contact.id} /> ); }); // 修正变量引用:将{ContactList}改为{renderContactList} return <div className="ui celled list">{renderContactList}</div>; }; export default ContactList;
另外注意文件名拼写:报错里出现了conatctList.js(少一个字母c),建议检查文件名与导入路径是否一致,避免因文件名拼写错误引发其他问题。
内容的提问来源于stack exchange,提问作者Sumit Kumar
相关产品推荐
相关产品推荐

