React路由访问ViewAll组件报Cannot read properties of undefined (reading 'map')错误
错误原因
- 你给ViewAll配置了独立路由,当直接通过路由跳转访问ViewAll时,没有父组件向它传递
inputs属性,导致props.inputs为undefined,调用map方法直接触发报错。 - InputForm的表单提交逻辑存在类型错误:你初始定义
inputData为数组类型,但formSubmitHandler里直接给setInputData传入了单个对象,会把inputData改为对象类型,对象不存在map方法,也会触发该报错。 - ViewAll组件没有做容错处理,传入非数组类型的值时会直接崩溃。
修复方案
1. 修复独立路由访问ViewAll的问题
如果需要单独通过路由访问ViewAll页面,直接在ViewAll内部发起请求获取接口数据,不需要依赖父组件传值:
import React, { useEffect, useState } from "react"; const ViewAll = (props) => { // 组件内部自己拉取数据 const [inputs, setInputs] = useState([]); useEffect(() => { fetch("http://localhost:3001/inputData") .then(res => res.json()) .then(data => setInputs(data)) }, []) return (<div> {/* 加可选链兜底,避免非数组报错 */} {inputs?.map((input) => ( <div key={input.id}> <p>First Name: {input.fName}</p> <p>Last Name: {input.lName}</p> <p>Email: {input.email}</p> <p>EID: {input.eid}</p> <p>Birthday: {input.birthday}</p> </div> ))} </div>); }; export default ViewAll;
2. 修复InputForm的提交逻辑
提交表单时要先把数据POST到mock接口,再重新拉取最新列表,不要直接覆盖inputData为对象:
const formSubmitHandler = (event) => { event.preventDefault(); if (!enteredFNameValid || !enteredLNameValid) { alert("First Name and Last Name accepts letters only."); return; } // 先提交数据到mock接口 fetch("http://localhost:3001/inputData", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fName: enteredFName, lName: enteredLName, email: enteredEmail, eid: enteredEid, birthday: enteredBirthday, }) }).then(() => { // 提交成功后重新拉取列表,更新inputData return fetch("http://localhost:3001/inputData") }).then(res => res.json()) .then(data => setInputData(data)) // 清空表单逻辑保留 setEnteredFName(""); setEnteredFNameTouch(false); setEnteredLName(""); setEnteredLNameTouch(false); setEnteredEmail(""); setEnteredEmailTouch(false); setEnteredEid(""); setEnteredEidTouch(false); setEnteredBirthday(""); setEnteredBirthdayTouch(false); };
3. 通用容错处理
如果ViewAll还是需要作为子组件使用,给inputs属性设置默认值为空数组,或者使用可选链?.map避免报错。
内容的提问来源于stack exchange,提问作者kelly-ghost_busters
相关产品推荐
相关产品推荐

