繁体   English   中英

无法显示数组项和标志错误:未捕获的类型错误:无法读取未定义的属性(读取“地图”)

[英]failed to display array items and flags error: Uncaught TypeError: Cannot read properties of undefined (reading 'map')

我是一个新手,仍然在 reactjs 周围调情。 为什么每当我尝试显示任务的数组内容时都会出现此错误。 这是我的 App.js

 import React from 'react'; import { useState } from 'react' import './index.css'; import Navbar from './components/layout/Navbar'; import Tasks from './components/Tasks'; // import Message from './components/Message'; // import FunctionClick from './components/FunctionClick'; const App = () => { const [tasks, setTasks] = useState([ { id: 1, text: 'This is the first text', day: 'Feb 5th at 2:30pm', reminder: true, }, { id: 2, text: 'Meeting at School', day: 'Feb 6th at 1:30pm', reminder: true, }, { id: 3, text: 'third meeting', day: 'Feb 6th at 1:30pm', reminder: true, }, ]) return ( <div className="container"> <Navbar /> <Tasks tasks={tasks}/> </div> ); } export default App;

这是我的 Tasks.js

 import React from 'react' import Task from './Task' const Tasks = ({tasks}) => { return ( <> {tasks.map((task) => ( <Task key={task.id} task={task} /> ))} </> ) } export default Tasks

任务.js

 import React from 'react' export const Task = ({task}) => { return ( <div className='task'> <h3>{task.text} </h3> </div> ) } export default Task;

它不会在控制台中显示错误,但会在浏览器中显示。 我被困住了。 请帮帮我。 您可以尝试在您的应用上进行测试。 谢谢

我想根据你的错误

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

如果您进行如下更改

const Tasks = ({tasks}) => { if(tasks && tasks.length > 0) { return ( <> {tasks.map((task) => ( <Task key={task.id} task={task} /> ))} </> ) } else return null; }

那么您可以跳过该错误,如您所见,我将 if 条件放入Tasks组件中以检查tasks数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM