NextJS组件传函数参数报错TypeError:t is not a function的解决
报错原因与解决方案
报错原因
你调用getGPSLocation时直接传递了一个回调函数,但该函数的定义要求接收一个包含callBackFn属性的对象。传参结构不匹配,导致函数内部的callBackFn实际为undefined,调用callBackFn(position)时就会抛出TypeError: t is not a function(混淆后的变量名t对应callBackFn)。
解决方案
以下两种方式任选其一即可解决问题:
方式一:调整调用代码,传递符合要求的对象参数
在组件的useEffect中,把回调函数包装成包含callBackFn属性的对象传入:
useEffect(() => { utl.getGPSLocation({ callBackFn: (v:{coords: {latitude:number; longitude:number;};}) => setCurrentGPS(v) }) }, [])
方式二:修改getGPSLocation的参数定义,直接接收回调函数
如果希望调用逻辑更简洁,可以调整函数的参数结构,直接接收回调函数而非对象:
function getGPSLocation( callBackFn: (v:{coords: {latitude:number; longitude:number;};}) => void ) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position: {coords: {latitude:number; longitude:number;};}) => { callBackFn(position) console.log('(U)position.coords.latitude='+JSON.stringify(position.coords.latitude)) console.log('(U)position.coords.longitude='+JSON.stringify(position.coords.longitude)) }); } else { console.log("Geolocation is not supported by this browser."); } }
修改后,原组件中的调用代码无需改动,可直接传递回调函数。
内容的提问来源于stack exchange,提问作者Michel
相关产品推荐
相关产品推荐

