LoginSignup
5
2

More than 5 years have passed since last update.

[React] リストアイテムに対するバケツリレーを recompose を使って軽減する

Last updated at Posted at 2018-07-23

Before

const Menu = ({ currentUserId, currentLocation, title, path }) => (...)

const MenuBlock = ({ currentUserId, currentLocation }) => (
  <MenuList>
    <Menu
      currentUserId={currentUserId}
      currentLocation={currentLocation}
      title="ホーム"
      path="/home"
    />
    <Menu
      currentUserId={currentUserId}
      currentLocation={currentLocation}
      title="お知らせ"
      path="/notifications"
    />
    <Menu
      currentUserId={currentUserId}
      currentLocation={currentLocation}
      title="設定"
      path="/setting"
    />
  </MenuList>
)

After

基本形

import { withHandlers } from 'recompose'

const Menu = ({ currentUserId, currentLocation }) => ({ title, path }) => (...)

const MenuBlock = withHandlers({ Menu })(({ Menu }) => (
  <MenuList>
    <Menu title="ホーム" path="/home" />
    <Menu title="お知らせ" path="/notifications" />
    <Menu title="設定" path="/setting" />
  </MenuList>
))

注意: displayName にこだわる場合は適宜関数に名前つけるなどしてください

pure を付与したい場合

import { withHandlers } from 'recompose'

const Menu = pure(({ currentUserId, currentLocation, title, path }) => (...))

const MenuBlock = withHandlers({
  Menu: (parentProps) => (props) => <Menu {...parentProps} {...props} />,
})(({ Menu }) => (
  <MenuList>
    <Menu title="ホーム" path="/home" />
    <Menu title="お知らせ" path="/notifications" />
    <Menu title="設定" path="/setting" />
  </MenuList>
))

できれば withHandlers の中で引数が分かれたまま pure() を当てたかったんですが, recompose の仕様上pureによって作られたクラスを関数として呼んでしまうことによりエラーが発生するので,こうするしかないみたいです。

5
2
0

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
5
2