简体   繁体   English

如何在数组中使用修饰符 function 和 typescript

[英]how to use modifier function with typescript in array

I tried to update my Todos I doesn't work.我试图更新我的待办事项,但我没有用。
I don't know what I did I made a mistake.我不知道我做了什么我犯了一个错误。

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;

you use a different type for Todos state and toDo in submit function. Please use the same type. Todos state 和 toDo in submit function 使用不同的类型。请使用相同的类型。 As you are assign a string to an object's array.当您将字符串分配给对象的数组时。

This is because of the destructuring happening in the argument of the onSubmit function, resulting in toDo being just a string, where toDos needs an object.这是因为在onSubmit function 的参数中发生了解构,导致toDo只是一个字符串,而toDos需要一个 object。

One way to solve this is to put that toDo string back inside an object that will then match the type ItoDoForm :解决此问题的一种方法是将该toDo字符串放回 object 中,然后匹配ItoDoForm类型:

setToDos((oldToDo) => [{ toDo }, ...oldToDo])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM