其实我有两个问题.首先,当我试图解决Lesson时,我得到了
"Type 'Lesson | Lesson[]' is not assignable to type 'Lesson'.
Type 'Lesson[]' is missing the following properties from type 'Lesson': name, note, hour, startDate, and 2 more."
父组件中的错误 这是我的父母公司.
import React, { useState, useEffect } from 'react'
import { Lesson } from './LessonType'
import NewLessonModal from './NewLesson';
function LessonList() {
const [lessons, setLessons] = useState<Lesson[]>([]);
const url = "https://localhost:7065/api/Lessons"
const addLesson = (lesson: Lesson[]) => {
setLessons([...lessons, lesson])
console.log(lesson)
}
}
return (
<div>
<NewLessonModal addLesson={addLesson} />
</div>
)
}
这是我的子元素公司.
import { ChangeEvent, useState } from "react";
import { Lesson } from './LessonType'
type Props = {
addLesson(lessonData: Lesson[]): void
}
function NewLessonModal({ addLesson }: Props) {
const [name, setname] = useState<string>("")
const [notes, setnotes] = useState<string>("")
const [startDate, setstartDate] = useState<string>("")
const [endDate, setendDate] = useState<string>("")
const [hour, sethour] = useState<number>(0)
const [certificate, setcertificate] = useState<string>("")
const [imagePath, setimagePath] = useState<string>("")
const [lessonData, setLessonData] = useState<Lesson[]>([])
const changeValue = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.name === "name") {
setname(event.target.value)
}
if (event.target.name === "notes") {
setnotes(event.target.value)
}
if (event.target.name === "startDate") {
setstartDate(event.target.value)
}
if (event.target.name === "endDate") {
setendDate(event.target.value)
}
if (event.target.name === "hour") {
sethour(Number(event.target.value))
}
}
const addNewLesson = () => {
setLessonData([
...lessonData,
{ name: name, note: notes, startDate: startDate, endDate: endDate, hour: hour, certificate: certificate, imagePath: imagePath }
]);
addLesson(lessonData)
}
return ....
课程类型文件为
export interface Lesson{
name:string,
note:string,
imagePath?:string,
hour:number,
startDate:string,
endDate:string,
certificate:string,
id?:number,
createdDate?:string
}
我无法修复此类型错误,我try 将数据传递给父组件.对象的第一个数组没有数据.第二遍数据处理我在父组件中获得第一个数据