我在 React 中编写了一个待办事项应用程序。我为多个部分创建组件。现在,每次我尝试运行该应用程序时,它都不会显示。
我总是收到错误 Uncaught TypeError: todo is undefined in footer.js:15。
我创建了一个待办事项列表应用程序,并将所有待办事项放入一个数组中,其中有使用状态待办事项。这是我在文件页脚中的组件 Todocounter 中传递的属性。
我尝试重命名该道具并更改其在页脚中的位置,以便在正确的位置调用。
这是app.js:
import React, { useState } from 'react'; import './App.css'; import InputTodos from './input.js'; import ListTodos from './list.js'; import TodoCounter from './footer.js'; import ClearButton from './clearbutton.js'; function App() { // create usestates for todos const [todo, setTodo] = useState([]); // render all components i have in diffrent files return (); } export default App;
这是 footer.js:
import React, { useEffect, useState } from 'react'; import './App.css'; // use effect to show whenever the array will change from completed todos to not completed function TodoCounter(props) { const { todo } = props; const [completed, setCompleted] = useState(0); const [notCompleted, setNotCompleted] = useState(0); // filter between completed todos and not completed todos with cheackking the bolean status function counttodos(props) { const { todo } = props; return { completed: todo.filter((todo) => todo.isChecked).length, notCompleted: todo.filter((todo) => !todo.isChecked).length, }; } //with the useeffect hook set the todos on completed or not completed if sth changes on the todos useEffect(() => { const { completed, notcompleted } = counttodos(todo); setCompleted(completed); setNotCompleted(notcompleted); }, [todo]); return (); } export default TodoCounter;Completed: {completed}
Not Completed: {notCompleted}
Todos: {todo.length}
将
counttodos
函数从组件中移出,这样它就不会在渲染时重新创建。因为你将todos
作为参数传递给该函数,并且它没有被包装在另一个对象中,所以你可以直接使用它而不需要解构:在组件本身中调用
counttodos
,并直接使用计算出的值而不将其存储为状态(参见@HenryWoody的评论):