我在 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 ( <div className="App"> <div className="container"> <div className="header"> <InputTodos todo={todo} setTodo={setTodo} /> </div> <div className="containerMid"> <ListTodos todo={todo} /> </div> <div className="footer"> <TodoCounter todo={todo} /> </div> <div className="buttonCleardiv"> <ClearButton todo={todo} setTodo={setTodo} /> </div> </div> </div> ); } 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 ( <div> <p>Completed: {completed}</p> <p>Not Completed: {notCompleted}</p> <p>Todos: {todo.length} </p> </div> ); } export default TodoCounter;
P粉0233267732023-09-09 17:19:26
將counttodos
函數從元件移出,這樣它就不會在渲染時重新建立。因為你將todos
作為參數傳遞給該函數,並且它沒有被包裝在另一個物件中,所以你可以直接使用它而不需要解構:
// 用布尔状态检查已完成和未完成的待办事项进行过滤 function counttodos(todos) { return { completed: todos.filter(todo => todo.isChecked).length, notCompleted: todos.filter(todo => !todo.isChecked).length, }; }
在元件本身中呼叫counttodos
,並直接使用計算出的值而不將其儲存為狀態(請參閱@HenryWoody的評論):
function TodoCounter({ todo }) { // 使用useEffect钩子在todos发生变化时设置已完成或未完成的todos const { completed, notcompleted } = counttodos(todo); return ( <div> <p>已完成:{completed}</p> <p>未完成:{notCompleted}</p> <p>待办事项:{todo.length} </p> </div> ); }