iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 25
0
自我挑戰組

Some thing with Reason系列 第 25

ReasonReact-題目未定

Demo

type item = {
  title: string,
  completed: bool
};

type state = {items: list(item)};

type action =
  | AddItem;

let component = ReasonReact.reducerComponent("TodoApp");

let newItem = () => {title: "Click a button", completed: true};

let make = (_children) => {
  ...component,
  initialState: () => {
    items: [
      {title: "Write some things to do", completed: false}
    ]
  },
  reducer: (action, {items}) =>
    switch action {
    | AddItem => ReasonReact.Update({items: [newItem(), ...items]})
    },
  render: (self) => {
    let numItems = List.length(self.state.items);
    <div className="app">
      <div className="title">
        (ReasonReact.string("What to do"))
        <button onClick=(_event => self.send(AddItem))>
          (ReasonReact.string("Add something"))
        </button>
      </div>
      <div className="items"> (ReasonReact.string("Nothing")) </div>
      <div className="footer">
        (ReasonReact.string(string_of_int(numItems) ++ " items"))
      </div>
    </div>
  }
};

initialState

React 稱為 getInitialState 在 Reason 中稱為 initialState

不需傳入參數,會回傳一個 state 類型

state 可以是任何類型 string, int, record ...etc

Actions and Reducer

在 React 中你會透過 callback handler 來修改 state

{
  /* ... other fields */
  handleClick: function() {
    this.setState({count: this.state.count + 1});
  },
  handleSubmit: function() {
    this.setState(...);
  },
  render: function() {
    return (
      <MyForm
        onClick={this.handleClick}
        onSubmit={this.handleSubmit} />
    );
  }
}

在 ReasonReact 你會將所有的 Function 整理在同一個地方

如果你看到 self.reduce 這是舊的 API

新的 API 是 self.send

  • action 是使用者定義的類型,他是一個 variant 類型,描述了所有可能的 state 類型
  • Component 的 state 可以透過 self.state 拿到
  • 只有一個 reducer 是 pattern-matches 會針對有可能的 action 去修改 reducer 得值
  • 在 reducer 中 self.handler 不允許狀態的改變,你必須使用 self.send 發送一個 action

上一篇
ReasonReact-PartIII
下一篇
ReasonReact- Render todo items
系列文
Some thing with Reason30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言