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>
}
};
React 稱為 getInitialState
在 Reason 中稱為 initialState
不需傳入參數,會回傳一個 state
類型
state
可以是任何類型 string, int, record ...etc
在 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 類型self.state
拿到self.handler
不允許狀態的改變,你必須使用 self.send 發送一個 action