0

下面是我正在学习的其中一个教程中使用的代码片段。有人可以帮助了解如何将参数“mediastate”传递给“notify”函数中的变量“transientListen”吗?

function createMediaListener(queries) {
  let transientListener = null;

  const keys = Object.keys(queries);

  const queryLists = keys.reduce((queryLists, key) => {
    queryLists[key] = window.matchMedia(queries[key]);
    return queryLists;
  }, {});

  const mediaState = keys.reduce((state, key) => {
    state[key] = queryLists[key].matches;
    return state;
  }, {});

  const notify = () => {
    if (transientListener != null) transientListener(mediaState);
  };

  const listeners = keys.reduce((listeners, key) => {
    listeners[key] = event => {
      mediaState[key] = event.matches;
      notify();
    };

    return listeners;
  }, {});

  const listen = listener => {
    transientListener = listener;
    keys.forEach(key => {
      queryLists[key].addListener(listeners[key]);
    });
  };

  const dispose = () => {
    transientListener = null;
    keys.forEach(key => {
      queryLists[key].removeListener(listeners[key]);
    });
  };

  const getState = () => mediaState;

  return { listen, dispose, getState };
}

export default createMediaListener;
4

1 回答 1

0

我的理解是,模块中的 return 语句调用了“listen”函数。问题是,“listen”函数需要一个参数,否则是:transientListener = listener; => 未定义。

于 2020-10-05T09:25:05.613 回答