【问题标题】:Wrap a function in useState在 useState 中包装一个函数
【发布时间】:2021-07-10 22:53:24
【问题描述】:

" Wrap getListViewSetting in a function for useState ",这是什么意思?

 const [isListView, setIsListView] = useState(
    getListViewSetting(location?.pathname?.replace('/', ''), true),
  );

【问题讨论】:

标签: reactjs


【解决方案1】:

无论谁(或任何工具)说这可能意味着您应该这样做:

const [isListView, setIsListView] = useState(
  () => getListViewSetting(location?.pathname?.replace('/', ''), true)
);

如果你将一个函数传递给useState,那么 react 将只调用该函数一次以确定初始值。如果getListViewSetting 的开销很大,那可以提高性能,因为您拥有的代码将需要在每次渲染时调用它,即使该值在第一次渲染时无用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多