我正在进行几个useSelector
调用,这些调用返回用于填充HIERARCHY
对象的数组。
const MyComponent = () => {
const one = useSelector(getArrayByName("Name1"));
const two = useSelector(getArrayByName("Name2"));
const three = useSelector(getArrayByName("Name3"));
const HIERARCHY = {
Levels: {
Name1: one.map(({ Name }) => Name),
Name2: two.map(({ Name }) => Name),
Name3: three.map(({ Name }) => Name)
},
};
// Use HIERARCHY
return ( … )
}
但是,在不同的组件中重复这样做很烦人。理想情况下,我想将HIERARCHY
一次存储在一个辅助文件或自定义挂钩中,然后将HIERARCHY
的填充版本导入任何组件中。
我不确定如何构造此自定义钩子或帮助文件,因为包含useSelector
调用的功能组件将返回JSX
,而不是填充的JavaScript
对象。有什么想法可以将useSelector
调用和HIERARCHY
对象的填充提取到外部文件吗?
我想要的:
import { HIERARCHY } from "./hierarchy_helper.js";
const MyComponent = () => {
// Use HIERARCHY
return ( … )
}
答案 0 :(得分:2)
自定义钩子是一个函数(通常从use开始),它可以返回您想要的任何内容(在您的情况下为HIERARCHY对象),还可以在其中调用其他钩子。文档中有示例:
https://reactjs.org/docs/hooks-custom.html
根据您的情况,您可以执行以下操作:
useMyCustomHook.js
const useMyCustomHook= () => {
const one = useSelector(getArrayByName("Name1"));
const two = useSelector(getArrayByName("Name2"));
const three = useSelector(getArrayByName("Name3"));
const HIERARCHY = useMemo({
Levels: {
Name1: one.map(({ Name }) => Name),
Name2: two.map(({ Name }) => Name),
Name3: three.map(({ Name }) => Name)
},
}, [one, two, three]);
return HIERARCHY;
}
MyComponent.jsx
const MyComponent = () => {
const HIERARCHY = useMyCustomHook();
// Use HIERARCHY
return ( … )
}