如何使用忽略回调参数的固定单个参数创建函数

时间:2019-04-01 16:30:49

标签: reactjs functional-programming lodash

我有这段代码:

const App = () => {
  const [selectedMovie, setSelectedMovie] = useState(null);
  return (
    <>
      <AppHeader onSearchClick={() => setSelectedMovie(null)} />
      <AppBody selectedMovie={selectedMovie} onMovieSelect={setSelectedMovie} />
      <AppFooter />
    </>
  );
};

最近我将重构为FP样式。为了使它看起来不错,我想避免在setSelectedMovie(null) lambda中调用onSearchClick

我想要实现的是传递一个函数,该函数将忽略onSearchClick参数,并使用固定的null进行调用,如下所示:

<AppHeader onSearchClick={setSelectedMovieCalledWithNullOnly} />

是否有可能,例如与lodash

1 个答案:

答案 0 :(得分:1)

您可以使用_.wrap()向该函数提供一个常量值:

const fn = x => console.log(x)
const alwaysNull = _.wrap(null, fn)

fn(5) // 5
alwaysNull(1243281) // null
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

如果可能还有其他参数,并且您要限制功能,则还可以使用_.ary()来将功能的Arity(该功能接受的参数数量)设置为0:< / p>

const fn = (...args) => console.log(args)
const alwaysNull = _.ary(_.wrap(null, fn), 0)

fn(5) // 5
alwaysNull(1, 2) // null
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

在您的情况下:

const App = () => {
  const [selectedMovie, setSelectedMovie] = useState(null);

  const setSelectedMovieCalledWithNullOnly = _.wrap(setSelectedMovie, null);

  return (
    <>
      <AppHeader onSearchClick={setSelectedMovieCalledWithNullOnly)} />
      <AppBody selectedMovie={selectedMovie} onMovieSelect={setSelectedMovie} />
      <AppFooter />
    </>
  );
};