-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (86 loc) · 2.11 KB
/
index.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
87
88
89
90
91
import './index.html';
import React from 'react';
import dva, { connect } from 'dva';
import { put, call } from 'dva/effects';
import { Router, Route, hashHistory } from 'dva/router';
import fetch from 'dva/fetch';
import styles from './index.less';
import SearchInput from './components/SearchInput';
import FriendList from './components/FriendList';
// 1. Initialize
const app = dva();
// 2. Model
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
app.model({
namespace: 'friends',
state: {
query: '',
friends: [],
},
subscriptions: [
function(dispatch) {
hashHistory.listen(location => {
if (location.action === 'POP') {
dispatch({
type: 'friends/setQuery',
payload: location.query.q,
});
}
});
}
],
effects: {
['friends/setQuery']: [function*({ payload }) {
yield delay(300);
yield call(hashHistory.push, {
query: { q: payload || '' },
});
const { success, data } = yield fetch(`/api/search?q=${payload}`)
.then(res => res.json());
if (success) {
yield put({
type: 'friends/setFriends',
payload: data,
});
}
}, { type: 'takeLatest' }],
},
reducers: {
['friends/setQuery'](state, { payload }) {
return { ...state, query: payload };
},
['friends/setFriends'](state, { payload }) {
return { ...state, friends: payload };
},
},
});
// 3. View
const App = connect(({ friends }) => ({
query: friends.query,
friends: friends.friends,
}))(function(props) {
function handleSearch(value) {
props.dispatch({
type: 'friends/setQuery',
payload: value,
});
}
return (
<div className={styles.app}>
<SearchInput
value={props.query}
placeholder="Search friends..."
handleSearch={handleSearch}
/>
<FriendList friends={props.friends} />
</div>
);
});
// 4. Router
app.router(({ history }) =>
<Router history={history}>
<Route path="/" component={App} />
</Router>
);
// 5. Start
app.start(document.getElementById('root'));