8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactで高階関数の連続適用をcomposeでいい感じに書く

Last updated at Posted at 2018-09-26

私は関数型が好きである。
といってもJavaScriptくらいしか関数型言語はかけないのだが。
それでも簡潔なインライン記法に出会ったときは感動した。
そんな関数型ラブな私でも関数型でイケてないと思う時がある。

読めない高階関数の連続適用

例えばReactでコンテナにreduxをconnectし、lifecycleでコールバックを仕込み、
さらにmaterial-uiのwithStylesでstyleを適用してexportしたい時があるとする。
まず素直に書こう。

import withStyles from '@material-ui/core/es/styles/withStyles';
import appStyle from '...'
import { connect } from 'react-redux';
import { lifecycle } from 'recompose';

// container
const App = () => ...

// redux接続用
const mapStateToProps = ...
const mapDispatchToProps = ...

export default connect(mapStateToProps, mapDispatchToProps)(lifecycle({...})(withStyles(appStyle)(App)));

うーん読めない。
ワンライナーじゃなく何行かで書くこともできるがそこまで変わらない気がする。
なによりエディタに今は助けてもらっているが、エディタなしで果たして書けるだろうか。

recomposeのcomposeとかいう神関数

ここでrecomopseという高階関数系をちょちょいとしてくれるライブラリが持っているcomposeが活躍する。
composeは関数のネストなくし可読性を大幅に上げてくれる。

import withStyles from '@material-ui/core/es/styles/withStyles';
import appStyle from '...'
import { connect } from 'react-redux';
import { lifecycle } from 'recompose';

// container
const App = () => ...

// redux接続用
const mapStateToProps = ...
const mapDispatchToProps = ...

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  lifecycle({...}),
  withStyles(appStyle),
)(App);

このようにcomposeの中に関数を並べるだけで順に適用してくれる。

まとめ

composeによって関数型のsucksな部分が解決できた。
recomopseは他にも関数型をいい感じにしてくれる関数がいっぱいある。
興味がある人は是非しらべてね。

※追記2018/09/27
@ygknさんからの情報提供。
composeはrecomposeだけじゃなくreduxも持っているためそちらでも可。

8
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?