[英]How to use a utility class instance in react different components and prevent reinitialization and only one instance is used on all components
I have a class in a separate file and two or more different react components that need to use the class methods我在一个单独的文件中有一个 class 和两个或多个需要使用 class 方法的不同反应组件
One approach was I initially created an instance of the class outside the react components to prevent re rendering and having re-initialize the class一种方法是我最初在反应组件之外创建了一个 class 的实例,以防止重新渲染并重新初始化 class
const utilityClass = new UtilityClass()
function ReactComponent() {
const doSomething = () => {
return utilityClass.doingSomething()
}
}
but then for the second react component in a different file I will have to do the same thing right like below但是对于另一个文件中的第二个反应组件,我将不得不像下面一样做同样的事情
const utilityClass = new UtilityClass()
function SecondReactComponent() {
const doSomething = () => {
return utilityClass.doingSomething()
}
}
Even though it wont re-initialize on component re-render I am still creating an instance of the utility class multiple times across the different react components so I tried useMemo
which also worked like below:即使它不会在组件重新渲染时重新初始化,我仍然在不同的反应组件中多次创建实用程序 class 的实例,所以我尝试
useMemo
,它也像下面一样工作:
function SecondReactComponent() {
const utilityClass = useMemo(() => new utilityClass(), []);
const doSomething = () => {
return utilityClass.doingSomething()
}
}
And I am wondering which is the best approach because I also tried useCallback
and for some reason that did not work and will appreciate if someone gave me more insights on the best practice to do this thanks我想知道哪个是最好的方法,因为我也尝试过
useCallback
并且由于某种原因没有奏效,如果有人给我更多关于执行此操作的最佳实践的见解,我将不胜感激
Just instantiate the class and export it at the top level of one of your modules.只需实例化 class 并将其导出到您的一个模块的顶层。 For example:
例如:
./First.jsx
: ./First.jsx
:
// class UtilityClass {/* ...*/}
export const utilityClass = new UtilityClass();
export function ReactComponent () {
const doSomething = () => {
return utilityClass.doingSomething();
};
}
Then, in every other module where you want to use it (in other components, etc.), just import and use it:然后,在您想要使用它的每个其他模块中(在其他组件等中),只需导入并使用它:
./Second.jsx
: ./Second.jsx
:
import {utilityClass} from './First';
export function SecondReactComponent () {
const doSomething = () => {
return utilityClass.doingSomething();
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.