类型的参数不能分配给'SetStateAction'类型的参数

时间:2020-08-07 02:37:19

标签: reactjs typescript


我有一个非常烦人的小问题,在使用useState的ReactJS和TypeScripts的选择形式中,它返回以下错误:
Argument of type '(ScheduleProps[] | { id: string; week_day: number; from: string; to: string; })[]' is not assignable to parameter of type 'SetStateAction<ScheduleProps[]>'.
  Type '(ScheduleProps[] | { id: string; week_day: number; from: string; to: string; })[]' is not assignable to type 'ScheduleProps[]'.
    Type 'ScheduleProps[] | { id: string; week_day: number; from: string; to: string; }' is not assignable to type 'ScheduleProps'.
      Type 'ScheduleProps[]' is missing the following properties from type 'ScheduleProps': id, week_day, from, to  TS2345

    51 |     });
    52 | 
  > 53 |     setScheduleItems(updatedScheduleItems);
       |                      ^
    54 |   }
    55 | 
    56 |   function handleCreateClass(e: FormEvent) {

错误在于“ setScheduleItems(updatedScheduleItems)”的返回中,这是我的代码段的一部分:

interface ScheduleProps {
  id: string;
  week_day: number;
  from: string;
  to: string;
}

const [scheduleItems, setScheduleItems] = useState<ScheduleProps[]>([
    {
      id: newId(),
      week_day: 0,
      from: '',
      to: '',
    },
  ]);

  // Update "week_day", "from" and "to"
  function setScheduleItemValue(
    position: number,
    field: string,
    value: string,
  ) {
    const updatedScheduleItems = scheduleItems.map((scheduleItem, index) => {
      if (index === position) {
        return { ...scheduleItem, [field]: value };
      }

      return scheduleItems;
    });

    setScheduleItems(updatedScheduleItems);
  }

0 个答案:

没有答案