概要
- hyperappにおいてviewが再描画されるタイミングはいつ?
- reactの【setState実行 -> state更新 -> コンポーネントをrender(再描画)】に当たる部分の処理の流れを知りたい。
reactの場合
import React from 'react'
import {render} from 'react-dom'
class Counter extends React.Component {
constructor() {
this.state = {
current : 0
}
}
countUp() {
this.setState({ // ★ 実行後にviewが再描画(render)される ★
current : current + 1
})
}
render() {
return (
<div>
current count : {this.state.current}
<button onClick={::this.countUp}>count up</button>
</div>
)
}
}
render(
<Counter />,
document.getElementById('count-up')
)
hyperappの場合
import {h, app} from 'hyperapp'
const state = {
current : 0
}
const actions = {
countUp : () => state => {
return { // ★ 実行後にviewが再描画される ★
current : state.current + 1
}
}
}
const view = (state, actions) => (
<div>
current count : {state.current}
<button onclick={actions.countUp}>count up</button>
</div>
)
app(
state,
actions,
view,
document.getElementById('count-up')
)
解説
- 「actions」に定義した関数の戻り値として渡されたオブジェクトを新たなstateとして、viewの再描画(render)が行われる
const state = {
current : 0
}
const actions = {
countUp : () => state => {
// reactの【 setState({ current : this.state.current + 1 }) 】に当たる
return {
current : state.current + 1
}
}
}
追記
試していく中で気づいて、自分的にすごくスッキリしたので記事にしましたが、公式のサンプルをしっかり読めばその時点で気付けそうなもんでしたね。