我有这段代码:
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
?
答案 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 />
</>
);
};