如何在reducer或自定义函数中使用netinfo



我正在使用react-native, expo和redux制作离线优先应用程序,我需要根据互联网连接将用户更改发送回服务器,所以我使用expo-background-fetch定期使用自定义函数或调度一些使用netInfo检查互联网连接作为完成工作的条件的操作来完成此任务,但它不起作用,因为总是说"错误:无效钩子调用。钩子只能在函数组件的内部调用。可以在reducer中,也可以在自定义函数中。

import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
import {sync} from './sync';
const BACKGROUND_FETCH_TASK = 'background-fetch';
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
const now = Date.now();

console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`);
sync();
// Be sure to return the successful result type!
return BackgroundFetch.BackgroundFetchResult.NewData;
});
async function registerBackgroundFetchAsync() {
console.log('registered');
return BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: 1, // 15 minutes
stopOnTerminate: false, // android only,
startOnBoot: true, // android only
});
}

这是在全局范围内的App.js文件上,然后在组件上,我用await registerBackgroundFetchAsync()注册了任务;我的sync。js文件是这样的

import {useNetInfo} from "@react-native-community/netinfo";
export function sync () {
const netInfo = useNetInfo();
}

有任何解决方案或解决方法吗?

看起来你不应该在defineTask回调中调用syncuseNetInfo意味着从React函数组件中调用。你可以使用其他不是钩子的方法。https://github.com/react-native-netinfo/react-native-netinfo#fetch可能是你的朋友。

最新更新