forked from dvajs/dva
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (87 loc) · 2.06 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
92
import './index.html';
import React from 'react';
import dva from '../../src/index';
import { connect } from '../../index';
import { Router, Route, useRouterHistory } from '../../router';
import fetch from '../../fetch';
import ProductList from './components/ProductList/ProductList';
import styles from './index.less';
// 1. Initialize
const app = dva();
// 2. Model
app.model({
namespace: 'products',
state: {
list: [],
loading: false,
},
subscriptions: {
setup({ dispatch }) {
dispatch({ type: 'query' });
},
},
effects: {
*query(_, { put }) {
const { success, data } = yield fetch(`/api/products`).then(res => res.json());
if (success) {
yield put({
type: 'querySuccess',
payload: data,
});
}
},
*vote({ payload }, { put}) {
const { success } = yield fetch(`/api/products/vote?id=${payload}`).then(res => res.json());
if (success) {
yield put({
type: 'voteSuccess',
payload,
});
}
},
},
reducers: {
query(state) {
return { ...state, loading: true, };
},
querySuccess(state, { payload }) {
return { ...state, loading: false, list: payload };
},
vote(state) {
return { ...state, loading: true };
},
voteSuccess(state, { payload }) {
const newList = state.list.map(product => {
if (product.id === payload) {
return { ...product, vote:product.vote + 1 };
} else {
return product;
}
});
return { ...state, list: newList, loading: false };
},
},
});
// 3. View
const App = connect(({products}) => ({
products
}))(function(props) {
return (
<div className={styles.productPage}>
<h2>Popular Products</h2>
<ProductList
data={props.products.list}
loading={props.products.loading}
dispatch={props.dispatch}
/>
</div>
);
});
// 4. Router
app.router(({ history }) =>
<Router history={history}>
<Route path="/" component={App} />
</Router>
);
// 5. Start
app.start('#root');