reactjs - 为什么我收到 TypeError: Cannot read property 'done' of undefined in todoapp?
问题描述
由于某种原因,我在我的简单反应待办事项应用程序中收到此错误:
知道如何解决吗?我看不到任何错误,而且我是 react 框架的初学者。我非常感谢任何帮助。非常感谢你们。
我还添加了所需的其余代码,因此请务必检查一下。
应用程序.js
import React, { useState,useRef,useEffect } from 'react';
import './App.css';
import TodoList from './TodoList';
import { v4 as uuidv4 } from 'uuid';
function App() {
const LOCAL_STORAGE_KEY = 'todoApp.todos'
const[todos,setTodos]=useState([{id:1,done:false,name:"todo1"}]);
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
if (storedTodos) setTodos(storedTodos)
}, [])
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
}, [todos])
const myRef=useRef();
function handleAddTodo(e){
e.preventDefault();
const name=myRef.current.value;
if (name==='') return
setTodos(prevTodos=>{
return [...prevTodos,{name:name,done:false,id:uuidv4()}]
})
myRef.current.value = null
}
function toggleTodo(id) {
const newTodos = [...todos]
const todo = newTodos.find(todo => todo.id === id)
todo.done = !todo.done
setTodos(newTodos)
}
return (
<>
<input ref={myRef} type="text"/><button onClick={handleAddTodo}>Add todo</button>
<TodoList todos={todos} toggleTodo={toggleTodo}/>
</>
);
}
export default App;
TodoList.js
import React from 'react'
import Todo from './Todo'
function TodoList({todos,toggleTodo}) {
return (
<div>
{todos.map(todo=>(
<Todo todo={todo} toggleTodo={toggleTodo}/>
)
)}
</div>
)
}
export default TodoList
Todo.js
import React from 'react'
function Todo({todo,toggleTodo}) {
function handleTodoClick(id){
toggleTodo(id)
}
return (
<div>
{todo.name} <input checked={todo.done} type="checkbox" onChange={handleTodoClick}></input>
</div>
)
}
export default Todo