我试图在React中创建一个参考服务组件,它将持有所有带有一堆数据的地图。我已经加载了数据,但是我不能从这个组件外部访问数据。
const ReferenceService = () => {
const dispatch = useDispatch();
const referenceTables = useSelector(selectReferenceTables);
const referenceServiceStatus = useSelector((state) => state.referenceService.status);
useEffect(() => {
if(referenceServiceStatus === 'idle'){
dispatch(loadReferenceTables())
}
}, [referenceServiceStatus, dispatch]);
const getReferenceTables = () => {
return referenceTables;
};
const getReferenceTable = (tableName) => {
return referenceTables[tableName];
};
}
export default ReferenceService;
I tried doing:
import ReferenceService from '../referenceService/ReferenceService';
const getRef = () => {
console.log(ReferenceService.getReferenceTables());
}
Unhandled Rejection (TypeError):referenceservice_referenceservice_webpack_importted_module_6_.default.getReferenceTables is not a function
我该如何重写这个组件以便我可以访问这些函数?
ReferenceService没有导出getReferenceTables,请将其导出或更改逻辑
找到解决办法了…
我只需要加上
return {getReferenceTables, getReferenceTable, getEntry};
到ReferenceService然后添加
const {getReferenceTables, getReferenceTable, getEntry} = ReferenceService();
到我想使用它的地方。