我在 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;
將
counttodos
函數從元件移出,這樣它就不會在渲染時重新建立。因為你將todos
作為參數傳遞給該函數,並且它沒有被包裝在另一個物件中,所以你可以直接使用它而不需要解構:在元件本身中呼叫
counttodos
,並直接使用計算出的值而不將其儲存為狀態(請參閱@HenryWoody的評論):