effects文档 https://dvajs.com/api/#effects
effects的里面的异步函数参数为:
*(action, effects) => void
[*(action, effects) => void, { type }]
/models/index.js
export default {
namespace: 'home',
state: {},
reducers: {},
effects: {
*asyncTable(action, effects) {},
*asyncTable({payload}, {put, yield, select}) {},
// 删除
*remove({ payload: id }, { call, put, select }) {
yield call(usersService.remove, id);
const page = yield select(state => state.users.page);
// put 等价于 dispatch action重新获取数据
yield put({ type: 'fetch', payload: { page } });
},
}
}
select
select(state => state)) ,state默认是所有的 state
*asyncTable(action, {call, put, select }) {
// 全局的 state
const state = yield select(state => state);
// 当前的 state
const state = yield select(state => state.home);
},
subscriptions
import * as usersService from '../services/users';
export default {
namespace: 'users',
state: {
list: [],
total: null,
},
reducers: {
save(state, { payload }) {
const { data: list, total } = payload;
return { ...state, list, total };
},
},
effects: {
*fetch({ payload: { page } }, { call, put }) {
// 请求接口
const { data, headers } = yield call(usersService.fetch, { page });
// action
yield put({
type: 'save',
payload: { data, total: headers['x-total-count'] }
});
},
},
subscriptions: {
setup({ dispatch, history }) {
// 监听路由,自动请求数据
return history.listen(({ pathname, query }) => {
if (pathname === '/users') {
dispatch({ type: 'fetch', payload: query });
}
});
},
},
};
在 subscriptions 中订阅路由变化,再通过 action 去重置状态会更合适
umi+dva完成 crud
https://github.com/sorrycc/blog/issues/62
https://github.com/umijs/umi-example-dva-user-dashboard
routerRedux
dispatch(routerRedux.push({
pathname: '/users',
query: { page },
}));