reactjs 类型X不能分配给类型Y

yjghlzjz  于 2022-12-22  发布在  React
关注(0)|答案(2)|浏览(205)

我有一个分类界面

export interface ISubCategory {
    _id: string,
    name: string,
    createdAt: Date,
    updatedAt: Date
}
export interface ICategory {
    _id: string,
    createdAt: Date,
    updatedAt: Date,
    name: string,
    subCategories: ISubCategory[],
    _v? : string | number
}

export interface ICategories{
    categories : ICategory[]
}

在我的主页上,我调用了API来获取类别

const fetchCategories = async () => {
    const data : ICategories = await getCategories()
    setCategories(data)
  }

  useEffect(() => {
    fetchCategories()
  }, [])

getCategories在这里

export async function getCategories (){
  try {
    const response = await axios.get('/categories')
    const data = response.data.data
    return data
  } catch (error) {
    console.log(error)
    return error
  }
}

当我把这些类别传递给子组件时,发生了一个错误。键入“ICategories|“[]"无法分配给类型”ICategory[]“。类型”ICategory“缺少类型”ICategory[]“的以下属性:length,pop,push,concat,以及其他29种类型。下面是我如何将类别传递给子组件并在子组件中接收它

return (
    <Div>
      <DropDownContextProvider>
        <Header categories={categories} />

         <Slider />
      </DropDownContextProvider>
    </Div>
  )

这是我接受它的方式

const Header = ({ categories }: ICategories ) => {
}

qij5mzcb

qij5mzcb1#

在返回响应中,您需要构建支持ICategories接口的对象

export async function getCategories (){
  try {
    const response = await axios.get('/categories')
    const data = response.data.data
    return {categories: data}
  } catch (error) {
    console.log(error)
    return {categories: []}

  }
}
ghg1uchk

ghg1uchk2#

类别是数组类型,并将界面更改为

export interface ISubCategory {
    _id: string,
    name: string,
    createdAt: Date,
    updatedAt: Date
   }
export interface ICategory {
    _id: string,
    createdAt: Date,
    updatedAt: Date,
    name: string,
    subCategories: ISubCategory[] | [],
    _v? : string | number
}

并删除了ICategories接口和类别状态设置为ICategory []| []

const [categories, setCategories] = useState<ICategory[] | []>([])
  const fetchCategories = async () => {
    const data = await getCategories()
    setCategories(data)
  }

  useEffect(() => {
    fetchCategories()
  }, [])

然后在报头组件中接收 prop ,如

const Header = ({ categories }: { categories:ICategory[] | [] }) => {
}

相关问题