说明
该实例是以dva命令创建的项目:$ dva new dva-quickstart
技术栈:dva + axios + redux-actions
路由
src/router.js
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import IndexPage from './routes/IndexPage';
import Products from './routes/Products';
import Counter from './routes/Counter';
import UserPage from './routes/UserPage';
function RouterConfig({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={IndexPage} />
<Route path="/products" exact component={Products} />
<Route path="/counter" exact component={Counter} />
<Route path="/user" exact component={UserPage} />
</Switch>
</Router>
);
}
export default RouterConfig;
UI Component
src/routers/UserPage.js:
import React from 'react';
import { connect } from 'dva';
import { userfetch } from '../actions';
const UserPage = (props) => {
const { userfetch } = props;
const { isFetch, error, user } = props.user;
let data = "";
if (isFetch) {
data = '正在加载中。。。'
} else if (user) {
data = user.data[0]['name'];
} else if (error) {
data = error.message;
}
function start() {
userfetch();
}
return(
<div>
<h1>User</h1>
<p>{data}</p>
<p>
<button onClick={start}>发送请求</button>
</p>
</div>
)
}
const mapStateToProps = (state) => ({
user: state.users
})
export default connect(mapStateToProps, { userfetch })(UserPage);
Model
src/models/user.js
import axios from 'axios';
export default {
namespace: 'users',
state: {
isFetch: false,
error: null,
user: null
},
effects: {
*'user/fetch'({ payload }, { call, put }) { // eslint-disable-line
yield put({ type: 'user/start' });
try {
const users = yield call(axios.get, 'https://11jsonplaceholder.typicode.com/users'); // axios.get('https://jsonplaceholder.typicode.com/users')
yield put({ type: 'user/sucess', uu: users });
} catch (e) {
yield put({ type: 'user/fail', errors: e });
}
},
},
reducers: {
'user/start'(state, action) {
return {
...state,
isFetch: true,
error: null,
user: null
};
},
'user/sucess'(state, action) {
return {
...state,
isFetch: false,
error: null,
user: action.uu
};
},
'user/fail'(state, action) {
return {
...state,
isFetch: false,
error: action.errors,
user: null
};
},
},
};
action(redux-actions)
src/actions/index.js
import { createAction } from 'redux-actions'; // 主要利用createAction这个方法
// counter
export const counterAdd = createAction('counter/add');
export const counterAsayAdd = createAction('counter/asayAdd');
// Products
export const productsDelete = createAction('products/delete');
// user
export const userfetch = createAction('users/user/fetch');
网友评论