【发布时间】:2023-01-21 05:48:28
【问题描述】:
我试图更新我的待办事项,但我没有用。
我不知道我做了什么我犯了一个错误。
ERROR in src/components/ToDoList.tsx:18:14
TS2345: Argument of type '(oldToDo: ItoDoForm[]) => (string | ItoDoForm)[]' is not assignable to parameter of type 'SetStateAction<ItoDoForm[]>'.
Type '(oldToDo: ItoDoForm[]) => (string | ItoDoForm)[]' is not assignable to type '(prevState: ItoDoForm[]) => ItoDoForm[]'.
Type '(string | ItoDoForm)[]' is not assignable to type 'ItoDoForm[]'.
Type 'string | ItoDoForm' is not assignable to type 'ItoDoForm'.
Type 'string' is not assignable to type 'ItoDoForm'.
16 | setValue("toDo", "");
17 | console.log(value.toDo);
> 18 | setToDos((oldToDo) => [value.toDo, ...oldToDo]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
19 | };
import { useState } from "react";
import { useForm } from "react-hook-form";
interface Iform {
toDo: string;
value: string;
}
interface ItoDoForm {
toDo: string;
}
function TodoList() {
const { register, handleSubmit, setValue } = useForm<Iform>();
const [toDos, setToDos] = useState<ItoDoForm[]>([]);
const onSubmit = ({toDo}: Iform) => {
setValue("toDo", "");
console.log(toDo);
**setToDos((oldToDo) => [toDo, ...oldToDo])**
//this setToDos doesn't work
};
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input
type='text'
{...register("toDo", {
required: "Please type what to do.",
minLength: {
value: 2,
message: "at least type a word",
},
})}
placeholder='Write what you want to do.'></input>
<button>Click</button>
</form>
<ul></ul>
</>
);
}
export default TodoList;
【问题讨论】:
-
在给您问题的那一行
toDo是string,但数组需要ItoDoForm。所以你应该把[toDo, ...oldToDo]换成[{ toDo }, ...oldToDo]。
标签: reactjs typescript