【问题标题】:Why is useMemo used in the Material-UI documentation for the autocomplete?为什么在 Material-UI 文档中使用 useMemo 来自动完成?
【发布时间】:2021-01-20 00:40:27
【问题描述】:

我在自动完成文档中特指this demo。

在谷歌地图示例中,有一个从useMemo 返回的节流函数,其中第二个参数为空数组。但是如果数组丢失,这里的记忆有什么意义呢?

const fetch = React.useMemo(
    () =>
      throttle((request, callback) => {
        autocompleteService.current.getPlacePredictions(request, callback);
      }, 200),
    [],
  );

在示例中替换此流程是否更有意义:

useEffect => useMemo => throttle => fetch

只需:

useEffect => 油门 => 获取

【问题讨论】:

  • 我不确定这是否能回答您的问题,但空数组意味着油门功能只会在挂载时初始化一次。否则,节流功能将在每次渲染时运行。
  • 并且 fetch 变量用于useEffect 的依赖项中,这就是它被记忆的原因。通常,当变量位于 useEffect 的依赖关系中时,useCallback/useMemo 是一个好主意。
  • useMemo 有第二个参数。一个空数组。如果您的意思是为什么该数组中没有任何内容,那意味着它在组件安装时创建一次,然后再也不会创建。如果他们没有把它放在备忘录中,那么每次组件渲染时,都会重新创建这个节流函数,从而打败节流点
  • @Jayce444 是的,这就是我的意思,谢谢。

标签: javascript reactjs autocomplete material-ui


【解决方案1】:

throttle 是函数创建者:

  • 它的作用:创建另一个函数,其作用是防止原始函数被重复调用。 (为了这个答案,定义被过度简化了)。

  • 它不做什么:以任何方式执行原始功能。

function throttle(fn, threshhold, scope) {
  return function () {
    let isInvokedRepeatedly = // some programming magic

    if (!isInvokedRepeatedly) {
      fn.apply(context, args);
    }
  };
}

所以如果你像这样在渲染方法中直接调用throttle()。

render() {
  const [inputValue, setInputValue] = React.useState('');
  const fetch = throttle(() => api.request(inputValue));

  ...
}

这意味着每次组件渲染时,都会重新创建一个新的 fetch 实例,从而重置节流函数的任何内部值。

这可以通过在第一次渲染时使用useMemo 或useCallback 仅实例化一次函数并传递一个空数组作为依赖项来解决。

render() {
  const [inputValue, setInputValue] = React.useState('');
  // You can also use React.useMemo()

  // memoize the callback. I personally prefer this method.
  const fetch = React.useCallback(throttle(() => api.request(inputValue)), []);

  // memoize the result which is the callback. Same as above
  const fetch1 = React.useMemo(() => {
    return throttle(() => api.request(inputValue));
  }, [] /* no dependency: callback only run once at startup */);

  ...
}

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2021-09-06
    • 2023-03-24
    • 2020-12-14
    • 2020-07-30
    • 1970-01-01
    • 2022-01-04
    • 2021-10-04
    • 2020-09-18
    相关资源
    最近更新 更多