LoginSignup
2
0

More than 5 years have passed since last update.

React + Context -> Rectx , a light-weight state manager.

Last updated at Posted at 2018-07-18

ReactのContext APIは場合によってはReduxを使わなくても良くなると思っているので使い勝手を追求したいと思ってたらRectxというのを見つけたので試してみました。

公式のREADMEにあるサンプルコード見ると ControllerListen というクラスが定義できるようです。パッと見 Controller に振る舞いを定義して Listen でViewを定義するような感じで個人的には昔懐かしいMVCフレームワークな香りを感じました。

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider, Controller, Listen } from 'rectx'

/**
 * we create a state machine `LikeController` inherit from Controller
 * define a class function `handleClick` for setting state by calling `this.setState`
 */
class LikeController extends Controller {
    state = {
        isLike: false,
        isMount: false
    }

    handleClick = () => {
        this.setState({
            isLike: !this.state.isLike
        })
    }
}

/**
 * a simple `<Like/>` react component with property `to` and `didMount`
 * @to:array, state machine arrays, this property can be set a bunch of `Machine`
 * @didMount:function, when `<Lisent/>` component mounted, it will be fired,
 * The arguments of didMount is the instances of `Machine` you just put in `to` property.
 */
const Like = () => (
    <Listen
        to={[LikeController]}
        didMount={like => {
            like.setState({ isMount: true })
        }}
    >
        {like => (
            <div>
                <button onClick={() => like.handleClick()}>Click me</button>
                <div>{like.state.isMount ? 'component being loaded' : 'component not loaded'}</div>
                <div>{like.state.isLike ? 'I love you' : 'I hate you'}</div>
            </div>
        )}
    </Listen>
)

/**
 * <Provider/> is necessary wrapper for this system.
 */
ReactDOM.render(
    <Provider>
        <Like />
    </Provider>,
    document.getElementById('root')
)

試しにRectxでToDoアプリを作ってみました。配列でControllerを渡せるみたいなので柔軟で且つStateが無秩序に増えるのを防げて個人的には丁度よい感じに思いました。

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