解决typescript报错:不能调用可能是未定义的对象

解决typescript报错:不能调用可能是未定义的对象,第1张

背景:当我们在react中封装组件并复用时,会传不同的props,那么自然有些props是不需要传的,所以在定义interface的时候需要加个问号。但这也就引来了标题的报错!

模拟一下报错代码:

// 父组件
const handleVisible () => {

}

export default function Father(props: IProps) {

	return (
		<Child/>
		<Child handleVisible={handleVisible}/>
	)
}
// 子组件
interface IProps {
	handleVisible?: () => void
}

export default function Child(props: IProps) {
	reutrn (
		// xxxxxxx
	)
	const getList = async () => {
		// 假设进行异步请求之后会调用父组件的``handleVisible``方法
		const res = await getlist()
		props.handleVisible() // 这段代码这个时候会报错!!!因为我们调用了两次子组件,只有一个传了handleVisible方法,所以ts不会让你执行
	}
}

解决方法也很简单:

1.先检查是否有该方法再执行。 即props.handleVisible && props.handleVisible()

2.类型断言。 即props.handleVisible!()

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1320763.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-11
下一篇2022-06-11

发表评论

登录后才能评论

评论列表(0条)

    保存