【问题标题】:how to use modifier function with typescript in array如何在数组中使用带有打字稿的修饰函数
【发布时间】: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;

【问题讨论】:

  • 在给您问题的那一行toDostring,但数组需要ItoDoForm。所以你应该把[toDo, ...oldToDo]换成[{ toDo }, ...oldToDo]

标签: reactjs typescript


【解决方案1】:

这是因为 destructuring 发生在 onSubmit 函数的参数中,导致 toDo 只是一个字符串,而 toDos 需要一个对象。

解决这个问题的一种方法是将 toDo 字符串放回一个对象中,然后该对象将匹配 ItoDoForm 类型:

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

【讨论】:

    【解决方案2】:

    您在提交功能中为 Todos 状态和 toDo 使用不同的类型。请使用相同的类型。当您将字符串分配给对象的数组时。

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 2022-01-26
      相关资源
      最近更新 更多