Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript useRef()的优点是什么,而不仅仅是在模块范围内声明变量?_Javascript_Reactjs - Fatal编程技术网

Javascript useRef()的优点是什么,而不仅仅是在模块范围内声明变量?

Javascript useRef()的优点是什么,而不仅仅是在模块范围内声明变量?,javascript,reactjs,Javascript,Reactjs,类似于,但我是在模块范围内而不是在功能范围内具体询问 e、 g 而不是 export const FunctionalComponent = ({children}) => { const webClientRef = useRef(axios.create()); ... webClientRef.current.get(...) ... } 除了能够引用仅在react组件中可用的内容之外,我真的看不到任何区别。或者仅将作用域限制在组件上。这将创建一个web

类似于,但我是在模块范围内而不是在功能范围内具体询问

e、 g

而不是


export const FunctionalComponent = ({children}) => {

   const webClientRef = useRef(axios.create());
   ...
   webClientRef.current.get(...)
   ...
}

除了能够引用仅在react组件中可用的内容之外,我真的看不到任何区别。或者仅将作用域限制在组件上。

这将创建一个webClient,而不管渲染多少组件:

const webClient = axios.create();

export const FunctionalComponent = ({children}) => {
   ...
   webClient.get(...)
   ...
}
这将为组件的每个实例提供一个:

export const FunctionalComponent = ({children}) => {

   const webClientRef = useRef(axios.create());
   ...
   webClientRef.current.get(...)
   ...
}

所以两者都有各自的用途。这只是您需要一个还是多个的问题。

这将创建一个webClient,而不管您渲染了多少组件:

const webClient = axios.create();

export const FunctionalComponent = ({children}) => {
   ...
   webClient.get(...)
   ...
}
这将为组件的每个实例提供一个:

export const FunctionalComponent = ({children}) => {

   const webClientRef = useRef(axios.create());
   ...
   webClientRef.current.get(...)
   ...
}

所以两者都有各自的用途。这只是需要一个还是多个的问题。

模块范围内的变量是静态的,在组件的所有实例之间共享。当需要访问呈现的DOM节点时,通常使用useRef,而不是React组件。模块范围内的变量是静态的,在组件的所有实例之间共享。通常使用useRef当您需要访问呈现的DOM节点(而不是React组件)时。