导入异步函数错误:钩子调用无效.钩子只能在函数组件的主体内部调用



我所想做的就是能够随时将逻辑从我的geolocationApi文件调用到我的react本地组件中,不喜欢HOOK但正常的异步函数,我在geolocationApi文件中使用自定义钩子不过我正在导入!(自定义挂钩处理mobx状态更新(

我想在我的功能组件中这样称呼它(简单明了(:

import geolocationApi from '@utils/geolocationApi.js'
const getCoords = async () =>
{
let result = await geolocationApi().requestLocationPermissions(true);
};

我的geolocationApi文件中有一堆关于geolocation的函数,我不想用来填充我的组件。

@utils/geolocationApi.js

import _ from 'lodash';
import Geolocation from 'react-native-geolocation-service';
import { useStore } from '@hooks/use-store';

const geolocationApi = () => {
//Custom hook that handles mobx stores
const root = useStore();

const requestLocationPermissions = async (getCityName = false) =>
{
const auth = await Geolocation.requestAuthorization("whenInUse");
if(auth === "granted")
{
root.mapStore.setLocationEnabled(true);
let coords = await getMe(getCityName);
return coords;
}
else
{
root.mapStore.setLocationEnabled(false);
}
};
const getMe = async () =>
{
Geolocation.getCurrentPosition(
async (position) => {
let results = await onSuccess(position.coords);
return results;
},
(error) => {
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
};

/*const onSuccess = async () => {}*/
};

export default geolocationApi;

这不会那么难!

如果我删除导出默认地理位置Api,而是在顶部添加导出常量地理位置Api:

geolocationApi.default.requestLocationPermissions is not a function

您不能在React组件之外使用钩子。您可以将状态传递给您的功能

import geolocationApi from '@utils/geolocationApi.js'
const getCoords = async (root) =>
{
let result = await geolocationApi(root).requestLocationPermissions(true);
};

然后不使用useStore()

import _ from 'lodash';
import Geolocation from 'react-native-geolocation-service';
import { useStore } from '@hooks/use-store';
// pass the root from top
const geolocationApi = (root) => {

// your logic
return {
requestLocationPermissions,
getMe
}
}

然后在组件树的某个地方,(一个使用useEffect的例子(

import getCoords from 'path'
const MyComp = () => {
const root = useStore();
useEffect(() => {
getCoords(root)
}, [root])
}

正如您所说,geolocationApi是一个常规函数,而不是React组件/钩子。因此,它不在React生命周期内处理其内部的钩子

您可以使用依赖注入概念来修复它。

使geolocationApi明显依赖于您的店铺。

const geolocationApi = (store) => {

然后将存储实例传递给它。


const getCoords = async (store) =>
{
let result = await geolocationApi(store).requestLocationPermissions(true);
};

无论React组件调用getCoords,都可以将存储传递给它

//...
const root = useStore();
getCoords(root);
//...

最新更新