forked from dvajs/dva
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (84 loc) · 2.01 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
import './index.html';
import React from 'react';
import dva from '../../src/index';
import { connect } from '../../index';
import { Router, Route, useRouterHistory, routerRedux } from '../../router';
import fetch from '../../fetch';
import styles from './index.less';
import SearchInput from './components/SearchInput';
import FriendList from './components/FriendList';
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 1. Initialize
const app = dva();
// 2. Model
app.model({
namespace: 'friends',
state: {
query: '',
friends: [],
},
subscriptions: {
setup({ dispatch, history }) {
history.listen(location => {
dispatch({
type: 'setQuery',
payload: location.query.q,
});
});
},
},
effects: {
setQuery: [function*({ payload }, { put, call }) {
yield delay(300);
yield call(routerRedux.push, {
query: { q: payload || '' },
});
const { success, data } = yield fetch(`/api/search?q=${payload}`)
.then(res => res.json());
if (success) {
yield put({
type: 'setFriends',
payload: data,
});
}
}, { type: 'takeLatest' }],
},
reducers: {
setQuery(state, { payload }) {
return { ...state, query: payload };
},
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('#root');