我正在尝试使用map方法展示从useState钩子接收到的信息数组。当编写map函数时,会出现"Cannot invoke an expression whose type lacks a call signature."错误。如果我创建一个返回相同信息的函数并调用该函数,则不会出现错误。
export default function Portfolio() {
const [portfolioData, setPortfoloioData] = useState<IProject[] | []>([])
useEffect(() => {
const portfolio: IProject[] = getPortfolio()
setPortfoloioData(portfolio)
}, [])
//Function to display the map that works.
const displayBlocks = (portfolioData: IProject[]): JSX.Element[] => {
return portfolioData.map((item, index) =>
<ProjectBlock key={index} project={item} index={index} />
)
}
return (
<div className='text-center pt-3'>
<h1 className='pb-4'>Portfolio</h1>
//This works without error
{displayBlocks(portfolioData)}
//This shows the missing call signature error even though
//it is the same as what is returned by the displayBlocks function.
{portfolioData.map((item, index) =>
<ProjectBlock key={index} project={item} index={index} />
)}
</div>
)
}
我希望找出如何在返回部分内使用简单的地图显示信息,而无需调用其他函数。我做错了什么?
IProject[] | []
作为你的状态类型?IProject[]
仍然可以是一个空数组的类型,移除联合即可。 - Andrew Li