LoginSignup
3
0

More than 5 years have passed since last update.

hyperapp-nestableで作ったComponentをLazyComponentとして扱う

Last updated at Posted at 2018-05-01

hyperapp-nestableを使うと、1つのappを1つのComponentとして使うことができるようになります。つまり、グローバルではないstateとactionsを持つコンポーネントを作ることができます。

import nestable from 'hyperapp-nestable'
import { h, app } from 'hyperapp'

const state = {value: 0}
const actions = {
  up: () => ({value}) => ({value: value + 1}),
  down: () => ({value}) => ({value: value - 1})
}
const view = (state, actions) => (props, children) =>
  <div>
    <h1>{props.name}</h1>
    <p>{children}</p>
    <button onclick={actions.up}>+</button>
    <p>state.value</p>
    <button onclick={actions.down}>-</button>
  </div>
const Counter = nestable(state, actions, view)

app({}, {}, () =>
  <div>
    <Counter name='sosukesuzuki'>こんにちは</Counter>
  </div>)

最後のCounterは通常のコンポーネントとして扱うことができるようになります。

LazyComponents使えなくないかい

しかし、1.2.0から入ったLazy Componentsという機能を使うことができません。(Lazy Componentsについては過去に自分が紹介記事を書いてるので、こちらを御覧ください。)
使うために試行錯誤してみました。愚直にやっているのでもっと良い方法をご存知の方がいたらコメントで教えて欲しいです。

const state = {value: 0}
const actions = {
  up: () => ({value}) => ({value: value + 1}),
  down: () => ({value}) => ({value: value - 1})
}
const view = (props, children) => (globalState, globalActions) => (state, actions) =>
  <div>
    <h1>{props.name}</h1>
    <p>{children}</p>
    <button onclick={actions.up}>+</button>
    <p>state.value</p>
    <button onclick={actions.down}>-</button>
  </div>

const LazyConuter = (props, children) => (globalState, globalActions) => nestable(state, actions, () => view(props, children))

こうすることによってLazyComponentsとしてグローバルアクション/ステートを受け取れるようになります。

3
0
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
3
0