【问题标题】:What are the advantages of useRef() instead of just declaring a variable in the module scope?useRef() 而不是仅仅在模块范围内声明一个变量有什么好处?
【发布时间】:2021-06-11 02:05:03
【问题描述】:

类似于What are the advantages of useRef() instead of just declaring a variable?,但我是在模块范围而不是函数范围内专门询问。

例如

const webClient = axios.create();

export const FunctionalComponent = ({children}) => {
   ...
   webClient.get(...)
   ...
}

而不是


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

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

除了能够引用仅在反应组件中可用的东西之外,我真的看不出任何区别。或者只是将范围限制为组件。

【问题讨论】:

  • 模块范围的变量是静态的,并且在组件的所有实例之间共享。
  • useRef 通常在您需要访问渲染的 DOM 节点时使用 - 而不是 React 组件。

标签: javascript reactjs


【解决方案1】:

无论你渲染多少个组件,这都会创建一个 webClient:

const webClient = axios.create();

export const FunctionalComponent = ({children}) => {
   ...
   webClient.get(...)
   ...
}

这为组件的每个实例提供一个:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多