-
Notifications
You must be signed in to change notification settings - Fork 0
/
Counter.js
86 lines (74 loc) · 1.54 KB
/
Counter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { run } from 'rex';
function Counter(props) {
const { tasks, actions, count, num } = props;
return (
<div>
<div className="counter">
counte: {count}
</div>
<input type="number" value={num} onChange={actions.changeNum} />
<button onClick={actions.addNum.bind(null, 1)}>add one</button>
<button onClick={tasks.beginAdd}>begin add</button>
<button onClick={tasks.stopAdd}>stop add</button>
</div>
);
}
function tasks(actions) {
let taskId = null;
function* countinueAdd() {
while(true) {
const num = yield select(state => state.num);
yield put(actions.addNum(num))
yield delay(1000);
}
};
return {
*beginAdd() {
taskId = yield fork(countinueAdd);
},
*stopAdd() {
if (taskId) {
yield cancel(taskId);
taskId = null;
}
},
};
}
function reducer(state) {
const { count } = state;
return {
setCount(count) {
return {
...state,
count,
};
},
addNum(num) {
return {
...state,
count: count + num,
};
},
changeNum(e) {
const num = parseInt(e.target.value, 10);
return {
...state,
num,
};
},
};
}
const Counter = run({
view: Counter,
namespace: 'root/Counter',
initialState: { count: -1 },
tasks,
reducer,
*init(actions, tasks) {
const { response, error } = yield Request('/api/getInitCount');
if (!error) {
yield put(actions.setCount(response));
}
},
});
export default Counter;