React Native:如何在多导出函数的helper文件中操作Context共享数据
你遇到的运行报错,本质是两条硬性规则被违反:
- React Hook(包括
useContext)只能在React函数组件的函数体、或者自定义Hook的函数体内调用,普通纯JS工具函数没有和React组件实例绑定,调用Hook必然触发Invalid hook call错误。 - 模块顶层的代码在项目启动时就会执行,这个时间点React的ContextProvider根本还没完成挂载,就算能调用Hook,拿到的Context值也是null,根本拿不到有效的setState方法。
你不需要牺牲按需导入的灵活性,也可以合规实现helper操作Context的需求,以下三种方案均经过项目验证:
方案1:在Provider层暴露全局可引用的更新方法(侵入性最低,最适合异步工具函数场景)
你不需要在helper里调用useContext,只需要在初始化MyContext的Provider组件里,把内部维护的setState方法存到独立的模块作用域中,让所有外部文件(包括helper)都可以直接import引用。
第一步,修改MyProvider.js:
// MyProvider.js import React, {createContext, useState, useEffect} from 'react'; // 导出供组件读值的Context引用 export const MyContext = createContext(); // 单独导出可被任意模块引用的setter方法,初始为null export let contextSetter = null; export const MyProvider = ({children}) => { const [name, setName] = useState(''); const [address, setAddress] = useState(''); // Provider挂载完成后,把真实的setState方法赋值给外部可引用的变量 useEffect(() => { contextSetter = { setName, setAddress } }, []); return ( <MyContext.Provider value={{name, setName, address, setAddress}}> {children} </MyContext.Provider> ) }
第二步,修改MyHelper.js,保持所有函数独立导出,无需调用Hook:
// MyHelper.js import GeocoderOsm from 'react-native-geocoder-osm'; // 直接导入暴露的setter引用 import {contextSetter} from '../MyProvider'; // 完全保持独立导出的形式,支持其他文件按需导入 export const myChangeNameFunction = (newName) => { // 直接调用暴露的setter更新Context contextSetter?.setName(newName); } export const getGPSbyAddress = (place) => { GeocoderOsm.getGeoAddress(place).then((res) => { contextSetter?.setAddress(res); }).catch((e) => { console.log('error', e) }); } export const getAddressByGPS = (lat, lon) => { GeocoderOsm.getGeoCodePosition(lat, lon).then((res) => { contextSetter?.setAddress(res); }).catch((e) => { console.log('error', e) }); }
注意点: 一定要等MyProvider完成挂载、useEffect执行完成之后再调用helper函数,否则contextSetter还是null,加?.空值判断可以避免首屏调用的崩溃问题。
方案2:封装自定义Hook返回独立业务函数(完全符合React设计规范,无全局变量)
如果你不想用全局模块变量的方式,可以把所有需要操作Context的业务逻辑封装成一个自定义Hook,在这个Hook内部合规调用useContext,再把各个独立的业务函数作为返回值抛出去。组件只需要调用一次这个Hook,就能解构出所有需要的独立功能,和直接导入helper的体验几乎没有差别。
修改后的MyHelper.js写法:
// MyHelper.js import {useContext} from 'react'; import GeocoderOsm from 'react-native-geocoder-osm'; import {MyContext} from '../MyProvider'; // 自定义Hook,内部可以合规调用useContext export const useAppHelpers = () => { // 这里调用useContext完全符合规则,因为自定义Hook本质是React函数逻辑的复用 const {setName, setAddress} = useContext(MyContext); // 把各个独立的业务逻辑封装成普通函数返回 const myChangeNameFunction = (newName) => { setName(newName); } const getGPSbyAddress = (place) => { GeocoderOsm.getGeoAddress(place).then((res) => { setAddress(res); }).catch((e) => { console.log('error', e) }); } const getAddressByGPS = (lat, lon) => { GeocoderOsm.getGeoCodePosition(lat, lon).then((res) => { setAddress(res); }).catch((e) => { console.log('error', e) }); } // 返回所有独立方法,支持按需解构使用 return { myChangeNameFunction, getGPSbyAddress, getAddressByGPS } }
在MyScreen.js里的使用方式没有额外复杂度:
// MyScreen.js import React, {useContext} from 'react'; import {View, Text, Button} from 'react-native'; import {MyContext} from '../MyProvider'; // 导入自定义Hook import {useAppHelpers} from '../helpers/MyHelper'; const MyScreen = () => { const {address} = useContext(MyContext); // 一次性拿到所有需要的独立业务函数,按需解构 const {getGPSbyAddress} = useAppHelpers(); return ( <View> <Button title='Get GPS' // 直接调用函数,和之前直接导入helper的写法完全一致 onPress={() => getGPSbyAddress('London') } /> <Text>{address}</Text> </View> ); }
优势: 完全遵循React Hook的设计规则,没有全局变量泄漏,Context的数据流完全可追踪,不会出现状态不一致的问题。
方案3:纯函数解耦(最适合需要跨环境复用的工具函数)
如果你希望helper完全不依赖React、不依赖Context,甚至可以在React项目外的Node脚本里复用,就不要把更新Context的逻辑写在helper里。让helper只负责处理业务逻辑、返回Promise结果,由调用它的组件负责把结果写回Context。
这时候MyHelper.js是完全无React依赖的纯模块:
// MyHelper.js import GeocoderOsm from 'react-native-geocoder-osm'; // 所有函数只做业务处理,不碰任何React状态 export const getGPSbyAddress = (place) => { // 直接返回Promise,让调用方自己处理结果 return GeocoderOsm.getGeoAddress(place) .catch((e) => { console.log('error', e); throw e; }); } export const getAddressByGPS = (lat, lon) => { return GeocoderOsm.getGeoCodePosition(lat, lon) .catch((e) => { console.log('error', e); throw e; }); }
在MyScreen.js里的使用,调用helper之后自己把结果传给setter:
// MyScreen.js import React, {useContext} from 'react'; import {View, Text, Button} from 'react-native'; import {MyContext} from '../MyProvider'; // 直接导入纯函数helper import {getGPSbyAddress} from '../helpers/MyHelper'; const MyScreen = () => { const {address, setAddress} = useContext(MyContext); const handleGetGPS = async () => { // 调用helper拿到结果,自己负责更新Context const res = await getGPSbyAddress('London'); setAddress(res); } return ( <View> <Button title='Get GPS' onPress={handleGetGPS} /> <Text>{address}</Text> </View> ); }
优势: helper没有任何框架耦合,测试的时候可以直接脱离React环境调用,复用范围最广。
内容的提问来源于stack exchange,提问作者MarioGotti

