未捕获的类型错误:无法读取提交表单中未定义的属性(读取"长度")



我想在控制台中显示我的待办事项,当按下"Uncaught TypeError:无法读取未定义的属性(读取'length'),你能帮我吗?(

TodoApp.jsx

import { useReducer } from "react"
import { todoReducer } from "./todoReducer";
import { TodoList } from "./TodoList";
import { TodoAdd } from "./TodoAdd";

export const TodoApp = () => {
const initialState = [
{
id: new Date().getTime(),
description: "recolectar piedra de alma",
done: false,
},
{
id: new Date().getTime() * 3,
description: "recolectar piedra de infinito",
done: false,
},
];

const [todos, dispatchTodo] = useReducer(todoReducer, initialState);

const handleNewTodo = (todo) => {
console.log({todo});
};

return (
<>
<h1>
TodoApp (10) <small>Pendientes 2</small>
</h1>
<hr />

<div className="row">
<div className="col-7">
<TodoList todos={todos} />
</div>
</div>

<div className="col-5">
<h4>Agregar TODO</h4>
<hr />
<TodoAdd onNewTodo={handleNewTodo} />
</div>
</>
);
};

TodoAdd.jsx:

import { useForm } from '../hooks/useForm';

export const TodoAdd = ({ onNewTodo }) => {
const { description, onInputChange, onResetForm } = useForm({
description: ''
});
const onFormSubmit = ( event ) => {
event.preventDefault();
if ( description.length <= 1 ) return;
const newTodo = {
id: new Date().getTime(),
done: false,
description: description,
}
onNewTodo(newTodo);
onResetForm();
}

return (
<form onSubmit={ onFormSubmit }>
<input 
type="text" 
placeholder="¿Qué hay que hacer?"
className="form-control"
name="description"
value={ description }
onChange={ onInputChange }
/>
<button 
type="submit"
className="btn btn-outline-primary mt-1"
>
Agregar
</button>
</form>
)
}

从我的理解,描述永远不会到达作为属性的形式,因为当使用。长度它不返回任何数字,所以这就是为什么属性不满足,但我真的不知道该怎么做

useForm返回description
定义useForm可以解决这个问题

export const useForm = ({ description }) => {
const [newDescription, setNewDescription] = useState(description);
const onInputChange = (e) => {
setNewDescription(e.target.value);
};
const onResetForm = () => {
setNewDescription("");
};
return { description: newDescription, onInputChange, onResetForm };
};

最新更新